栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Excel VBA中使用数组或字典作为SQL中的FROM子句

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Excel VBA中使用数组或字典作为SQL中的FROM子句

扩展@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
上的第一行包含列标题的范围内。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/366237.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号