|
楼主 |
发表于 2014-1-10 12:26
|
显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
本帖最后由 335081548 于 2014-1-10 12:29 编辑
二个工作簿中数据连接要求:
用SQL语句 将辅助表里面的全部信息黏贴到明细表,并关联inner表里面的 inner数据
SQL语句代码
- SELECT A.货号,名称,陈列图指示,B.inner FROM [C:\Documents and Settings\admin\桌面\两表合并\辅助.xlsx].[基础信息$]A Inner Join [C:\Documents and Settings\admin\桌面\两表合并\Select.xlsm].[inner$]B ON A.货号=B.sku
复制代码 最后结果示意图
VBA代码如下:
- Sub Test4()
- Dim Conn As Object, Rst As Object
- Dim strConn As String, strSQL As String
- Dim i As Integer, PathStr As String
- Set Conn = CreateObject("ADODB.Connection")
- Set Rst = CreateObject("ADODB.Recordset")
- PathStr = ThisWorkbook.FullName '设置工作簿的完整路径和名称
- Select Case Application.Version * 1 '设置连接字符串,根据版本创建连接
- Case Is <= 11
- strConn = "Provider=Microsoft.Jet.Oledb.4.0;Extended Properties=excel 8.0;Data source=" & PathStr
- Case Is >= 12
- strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathStr & ";Extended Properties=""Excel 12.0;HDR=YES"";"""
- End Select
- '设置SQL查询语句
- Conn.Open strConn '打开数据库链接
- strSQL = "SELECT A.货号,名称,陈列图指示,B.inner FROM [" & ThisWorkbook.Path & "\辅助.xlsx].[基础信息$]A Inner Join [" & ThisWorkbook.Path & "\Select.xlsm].[inner$]B ON A.货号=B.sku"
- Set Rst = Conn.Execute(strSQL) '执行查询,并将结果输出到记录集对象
- With Sheets("明细").Range("A2:D" & Rows.Count)
- .Cells.Clear
- ' For i = 0 To Rst.Fields.Count - 1 '填写标题
- ' .Cells(1, i + 1) = Rst.Fields(i).Name
- ' Next i
- .Range("A1").CopyFromRecordset Rst
- .Cells.EntireColumn.AutoFit '自动调整列宽
- End With
- Rst.Close '关闭数据库连接
- Conn.Close
- Set Conn = Nothing
- Set Rst = Nothing
- End Sub
复制代码
SQL语法如下:- SELECT 要显示的字段 FROM [文件路径\工作簿名1.扩展名].[工作表名1$]A Inner Join [文件路径\工作簿名2.扩展名].[工作表名2$]B ON A.公共字段=B.公共字段
复制代码
|
|