类似于:Convert Variant Array to String - 但接受的答案在我的案例中不起作用。
我的代码:
SQLStr = "SELECT lineID FROM alldata where asdf = '" & asdf & "'"
Set rs = New ADODB.Recordset
rs.Open SQLStr, conn, adOpenStatic
Dim arr
Dim arrString
rs.MoveFirst
arr = rs.GetRows
arrString = Join(arr, ", ")
在语句arr = rs.GetRows
执行后,它在我的控制台中具有以下值:
我试图加入这两个值,用comma space
分隔成一个字符串,所以最终的结果是:
arrString = "25616, 99607"
但是,当我运行Invalid procedure call or argument
行时,出现Join
错误。我做错了什么?
答案 0 :(得分:1)
虽然我确信有一种更优雅的方式来完成您的任务,但我确实编写了一些似乎正在成功运行的代码。
Option Explicit
Private Sub TestArray()
Dim arr(0, 1) As Variant 'Mimic the structure of your array
Dim arrString As String
Dim sDelimiter As String
Dim j As Long
'Mimic the structure of your array
arr(0, 0) = "25616"
arr(0, 1) = "99607"
sDelimiter = ", " 'Set your delimiter
'Loop through the inner array
For j = 0 To UBound(arr, 2)
'Concatenate the elements
arrString = arrString & sDelimiter & arr(0, j)
Next j
'Remove the leading delimiter / cleanup
arrString = Replace(arrString, sDelimiter, "", 1, 1, vbTextCompare)
MsgBox arrString
End Sub
有趣的代码来自sDelimiter = ", "
及以下。
我无法弄清楚如何将数组Transpose
转换为一维数组(来自二维数组的数组),所以我决定循环遍历内部数组并连接值。
连接会在列表的前面生成一个额外的分隔符,因此有一行代替该分隔符。
答案 1 :(得分:0)
Join只接受1-d数组。这是一种非循环方式,可以将记录集转换为以逗号分隔的字符串。
Application.Transpose
GetRows将数据置于错误的行/列方向。您可以使用QSharedMemory
来做到正确,但是您仍然无法将其传递给加入,因为它是2D。
GetString返回tab / lf分隔的字符串。我在选项卡上拆分它,然后在逗号空间重新加入它,这很好。
答案 2 :(得分:0)
就在2天前,有一个question促使我编写了一个函数,我称之为MultiSplit()
,它接受一个字符串和2个分隔符并将其拆分为二维数组。这个当前的问题需要一种逆转:
Function MultiJoin(A As Variant, Optional ItemDelimiter As String = ",", Optional RowDelimiter As String = ";") As String
'assumes that A is a 2-dimensional array of strings
Dim s As String, i As Long, j As Long
Dim lb1 As Long, lb2 As Long, ub1 As Long, ub2 As Long
lb1 = LBound(A, 1)
lb2 = LBound(A, 2)
ub1 = UBound(A, 1)
ub2 = UBound(A, 2)
For i = lb1 To ub1
For j = lb2 To ub2
s = s & A(i, j) & IIf(j < ub2, ItemDelimiter, "")
Next j
s = s & IIf(i < ub1, RowDelimiter, "")
Next i
MultiJoin = s
End Function
测试如下:
Sub test()
Dim A As Variant
ReDim A(0 To 0, 0 To 1)
A(0, 0) = "25616"
A(0, 1) = "99607"
Debug.Print MultiJoin(A, ", ")
ReDim A(0 To 1, 0 To 1)
A(0, 0) = 1
A(0, 1) = 2
A(1, 0) = 3
A(1, 1) = 4
Debug.Print MultiJoin(A, " ", vbCrLf)
End Sub
输出:
25616, 99607
1 2
3 4
答案 3 :(得分:0)
在Excel中,您可以使用Index
切片并返回1D数组
Dim arr(0, 2) As Variant
arr(0, 0) = "25616"
arr(0, 1) = "99607"
arr(0, 2) = "12345"
MsgBox Join(Application.Index(arr, 0), ", ")