|
- Sub main()
- ' 设置wb为当前工作簿
- Set wb = Application.ThisWorkbook
- '' 设置sht为指定名称的工作表,引号内填写工作表名称
- Set sht = wb.Worksheets("原数据")
- ' 设置psht为工作表,在引号内填写工作表名称
- Set psht = wb.Worksheets("目标表样")
- ' 设置范围为A2单元格
- Set rng = psht.Range("A2")
- ' 获取工作簿的完整路径,赋值给fp
- fp = wb.FullName
- SQL = "SELECT 品名,型号,left(型号,1) as 区域 From [" & sht.Name & "$a1:b]"
- SQL = " transform first(型号) select 品名 from(" & SQL & ") group by 品名,型号 pivot 区域"
- Debug.Print SQL
- SqlToRng fp, SQL, rng
- End Sub
- ' 过程结束
- '' 代码功能:根据SQL语句查询结果 输出到目标单元格区域
- '' 参数说明
- '' 参数【Datapath 】:工作簿的文件路径
- '' 参数【 SQL 】:SQL查询语句
- '' 参数【 Rng 】:目标单元格区域
- '' 调用示范:SqlToRng fp,sql,rng
- Sub SqlToRng(ByVal DataPath As String, ByVal SQL As String, ByVal rng As Range)
- 'Debug.Print SQL
- '' 判断工作簿路径是否存在,若不存在弹窗提示,退出函数
- If Len(DataPath) = 0 Or Len(Dir(DataPath)) = 0 Then
- MsgBox "数据源地址为空或者数据源文件不存在!", vbInformation, "QQ84857038"
- '' 退出
- Exit Sub
- End If
- '' 判断SQL语句是否为空
- If Len(SQL) = 0 Then
- MsgBox "SQL语句不能为空!", vbInformation, "QQ84857038"
- '' 退出
- Exit Sub
- End If
- '' 声明连接器变量cnn,结果集变量rs,引擎字符串变量dataEngine
- Dim CNN, rs, dataEngine As String
- '' 判断Excel版本,选择相应的引擎
- Select Case Application.Version * 1
- Case Is <= 11
- dataEngine = "Provider=Microsoft.Jet.Oledb.4.0;Extended Properties='Excel 8.0;HDR=YES;IMEX=2';Data Source="
- Case Is >= 12
- dataEngine = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES;IMEX=2'; Data Source= "
- End Select
- '' 创建ADO Connection 连接器
- Set CNN = CreateObject("ADODB.Connection")
- '' 打开数据源
- CNN.Open dataEngine & DataPath
- '' 执行查询,返回记录集
- Set rs = CNN.Execute(SQL)
- '' 把数据集转置为一个数组
- If Not (rs.EOF And rs.BOF) Then
- rng.CopyFromRecordset rs
- End If
- '' 关闭记录集
- rs.Close
- '' 关闭连接器
- CNN.Close
- '' 释放对象
- Set rs = Nothing
- Set CNN = Nothing
- End Sub
复制代码 |
|