|
本帖最后由 autumnalRain 于 2015-10-29 10:33 编辑
我在EXCLE中直接用SQL语句,运行没有问题
- Select 序号,姓名,性别,null as 学历,年龄 from [部门A$] UNION ALL
- Select 序号,姓名,性别,null as 学历,年龄 from [部门B$] UNION ALL
- Select 序号,姓名,性别,学历,年龄 from [部门C$]
复制代码
但当我把它粘贴至VBA SQL中时却常报错,提示“未定义变量”……什么也没有修改……过了半小时重新打开——竟然可以运行!
- Sub INNERJOIN()
- Dim ADORST As Object
- Set AdoConn = CreateObject("ADODB.Connection")
- conn = "provider=microsoft.ACE.OLEDB.12.0;extended properties='Excel 12.0;hdr=yes';data source=" & ThisWorkbook.FullName
- Sql = "Select 序号,姓名,性别,null as 学历,年龄 from [部门A$] UNION ALL Select 序号,姓名,性别,null as 学历,年龄 from [部门B$] UNION ALL Select 序号,姓名,性别,学历,年龄 from [部门C$]"
- AdoConn.Open conn
- Set ADORST = AdoConn.Execute(Sql)
- For k = 0 To ADORST.Fields.Count - 1
- Sheets("全部合并").Cells(14, k + 1) = ADORST.Fields(k).Name
- Next k
- Sheets("全部合并").Range("A15").CopyFromRecordset ADORST
- ADORST.Close
- AdoConn.Close
- Set ADORST = Nothing
- Set AdoConn = Nothing
- End Sub
复制代码 各位老师指导,这是什么原因?
|
|