是否可以在SQL语句中使用数组或字典作为表。
例如,strSQL =“ SELECT * FROM”&myArray&“”
提前致谢。
扩展@Nathan_Sav提供的想法,应将以下代码应用于它:
Dim a(3) As String a(0) = "1 as C1" a(1) = 2 a(2) = 3 a(3) = 4 Debug.Print "select * from (SELECT " & Join(a, " UNION ALL SELECT ") & ") as tmp"
这是一个简短的子代码,用于手动连接/构造必要的字符串:
Option Explicit Sub tmpTest() Dim strSQL As String Dim varArray As Variant Dim lngRow As Long, lngColumn As Long varArray = ThisWorkbook.Worksheets(1).Range("A1:G12") strSQL = "select * from " strSQL = strSQL & "(select " For lngRow = LBound(varArray, 1) + 1 To UBound(varArray, 1) For lngColumn = LBound(varArray, 2) To UBound(varArray, 2) 'First row must contain column names If lngRow = LBound(varArray, 1) + 1 Then strSQL = strSQL & varArray(lngRow, lngColumn) & _ " as [" & varArray(lngRow - 1, lngColumn) & "], " Else strSQL = strSQL & varArray(lngRow, lngColumn) & ", " End If 'Beyond the last column a UNION ALL SELECT must be added ' except for the last row If lngColumn = UBound(varArray, 2) And _ lngRow < UBound(varArray, 1) Then strSQL = Mid(strSQL, 1, Len(strSQL) - 2) & _ " union all select " End If Next lngColumn Next lngRow strSQL = Mid(strSQL, 1, Len(strSQL) - 2) & ") as tmp" Debug.Print strSQL End Sub
上面的代码假定数据在sheet1A1:G12上的第一行包含列标题的范围内。
A1:G12