我正在寻找一种方法来按字母顺序将字符串(从单元格中)添加到字符串数组。
例如:
string array = {"apple", "banana", "orange"}
添加“樱桃”
:
string array = {"apple", "banana", "cherry", "orange"}
因此,如果我执行 sheets(1).range("A1").value = new string array
,整个数组将在一个单元格中。
我在网上找到了一个按字母顺序对所选单元格进行排序的功能,但不确定它是否对我的实例有帮助。
Function Alphabetize(vStrings As Variant, separator As String) As String
Dim v As Variant, vSorted As Variant
Dim i As Long, j As Long, n As Long
Dim bDone As Boolean
For Each v In vStrings
n = n + 1
Next
ReDim vSorted(1 To n)
ReDim pos(1 To n)
For Each v In vStrings
i = i + 1
vSorted(i) = v
Next
For j = 2 To n
bDone = True
For i = 2 To n
If vSorted(i) < vSorted(i - 1) Then
v = vSorted(i - 1)
vSorted(i - 1) = vSorted(i)
vSorted(i) = v
bDone = False
End If
Next
If bDone Then Exit For
Next
For i = 1 To n
If vSorted(i) <> "" Then
If i = 1 Then
Alphabetize = separator & vSorted(i)
Else
If vSorted(i) <> vSorted(i - 1) Then Alphabetize = Alphabetize & separator & vSorted(i)
End If
End If
Next
Alphabetize = Mid$(Alphabetize, 2)
End Function
最佳答案
如果需要,您可以使用 .NET
库中的 System.Collections.SortedList
类。然后就不用担心排序了。
Dim objList As Object
Set objList = CreateObject("System.Collections.SortedList")
objList.Add "apple", ""
objList.Add "banana", ""
objList.Add "orange", ""
objList.Add "cherry", ""
Dim i As Long
For i = 0 To objList.Count - 1
Debug.Print objList.GetKey(i)
Next
打印:
apple
banana
cherry
orange
如果您想将这些值组合成一个字符串,只需在循环遍历这些值时将它们连接起来,或者您可以转移到一个数组并使用 Join
来创建字符串:
ReDim a(objList.Count - 1) As String
Dim i As Long
For i = 0 To objList.Count - 1
a(i) = objList.GetKey(i)
Next
' Combine strings into the format: {"string1", "string2", "stringN"}
Sheet1.Range("A1").Value = "{""" & Join(a, """, """) & """}"
关于arrays - 按字母顺序添加到字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31689163/