扩展@Nathan_Sav提供的想法,应将以下代码应用于它:
更新:Dim a(3) As Stringa(0) = "1 as C1"a(1) = 2a(2) = 3a(3) = 4Debug.Print "select * from (SELECt " & Join(a, " UNIOn ALL SELECT ") & ") as tmp"
这是一个简短的子代码,用于手动连接/构造必要的字符串:
Option ExplicitSub tmpTest()Dim strSQL As StringDim varArray As VariantDim lngRow As Long, lngColumn As LongvarArray = 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 lngColumnNext lngRowstrSQL = Mid(strSQL, 1, Len(strSQL) - 2) & ") as tmp"Debug.Print strSQLEnd Sub
上面的代码假定数据在sheet1
A1:G12上的第一行包含列标题的范围内。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)