我尝试将系统,帐号和WorkOrder字段从电子表格导出到Access 2007中的表,只要WorkOrder字段不匹配即可。
到目前为止,我一直在收到错误消息,说明'"不是有效的名称'。是否发生这种情况是因为tblTest的字段多于Excel记录集?我不知所措。
Dim xlString As String
xlString = "[Excel 8.0;HDR=YES;DATABASE="
Set cn = CreateObject("ADODB.Connection")
dbPath = Application.ActiveWorkbook.Path & "\SA Daily October.accdb"
dbWB = Application.ActiveWorkbook.FullName
dbWs = Application.ActiveSheet.Name
scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
dsh = "[" & Application.ActiveSheet.Name & "$]"
destTable = "tblTest"
destTablePath = dbPath & "]." & "[" & destTable & "]"
xlSheet = xlString & dbWB & "]." & dsh
cn.Open scn
ssql = "INSERT INTO tblTest ([System], [Account Number], [WorkOrder])"
ssql = ssql & " SELECT " & xlSheet & ".[System], "
ssql = ssql & xlSheet & ".[Account Number], "
ssql = ssql & xlSheet & ".[WorkOrder] FROM " & xlSheet
ssql = ssql & " WHERE NOT EXISTS (SELECT [System], [Account Number], [WorkOrder] FROM [" & destTablePath & " WHERE [" & destTablePath & ".[WorkOrder] = "
ssql = ssql & xlSheet & ".[WorkOrder])"
cn.Execute ssql
答案 0 :(得分:0)
检查WHERE
子句子查询中数据库路径名称周围的括号。他们没有正确关闭。实际上,由于使用ADO连接到数据库,因此不需要.accdb文件的绝对路径引用。
在执行查询之前使用debug.Print ssql
,以便更好地检查立即窗口中字符串输出的标点符号。如果找不到它,请转到VBA IDE菜单:View / Immediate Window或Ctrl + G:
ssql = "INSERT INTO tblTest ([System], [Account Number], [WorkOrder])"
ssql = ssql & " SELECT " & xlSheet & ".[System], "
ssql = ssql & xlSheet & ".[Account Number], "
ssql = ssql & xlSheet & ".[WorkOrder] FROM " & xlSheet
ssql = ssql & " WHERE NOT EXISTS (SELECT [System], [Account Number], [WorkOrder] "
ssql = ssql & " FROM [" & destTablePath & " WHERE [" & destTablePath & ".[WorkOrder] = "
ssql = ssql & xlSheet & ".[WorkOrder])"
Debug.Print ssql
顺便说一句,如果不是efficiency,您可以避免WHERE NOT EXISTS
子查询LEFT JOIN ... NULL
的可读性。
INSERT INTO tblTest ([System], [Account Number], [WorkOrder])
SELECT [ExcelTable].[System], [ExcelTable].[Account Number], [ExcelTable].[WorkOrder]
FROM [ExcelTable] LEFT JOIN tblTest
ON [ExcelTable].WorkOrder = tblTest.WorkOrder
WHERE [tblTest].WorkOrder Is Null