【发布时间】:2019-03-12 20:37:51
【问题描述】:
我正在尝试将数据从一个 Excel 工作簿复制到另一个。为此,我正在使用 ADODB 连接。通过 SQL 查询,我将所有数据从我想要的工作表复制到另一个工作簿。但是,由于某种原因,它会跳过每张纸的第一行。因此,复制的数据总是从第 2 行开始。 也许你们中的某个人可以发现我的错误或向我解释为什么会发生这种情况?
Sub ImportExcelSQL()
Dim sheetName, sheetNewName, filepath, strConnection, Sql As String
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
'-------- Close workbook updates ----------
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
Application.StatusBar = "Importing...."
'------------------------------------------
filepath = Range("filepath")
strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _
& "DBQ=" + filepath + ";"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open connection
conn.Open strConnection
' Loop through the sheets
Dim i As Integer
i = 1
Do Until IsEmpty(Range("importSheetNames").Offset(i, 0))
If Range("importSaveSheetFlags").Offset(i, 0).Value = "Y" Then
' Get sheet names and input variables"
sheetName = Range("importSheetNames").Offset(i, 0).Value
sheetNewName = Range("exportSheetNames").Offset(i, 0).Value
filepath = Range("filepath")
' Clear data sheet
Sheets(sheetNewName).UsedRange.ClearContents
' ----------------------- SQL CODE ----------------------------
Sql = "SELECT * FROM [" + sheetName + "$A:CA]"
'Sql = "SELECT * FROM [" + sheetName + "$A1:CA1000]" 'Does not do any difference
' Open the connection and execute.
'conn.Open strConnection
Set rs = conn.Execute(Sql)
' Check we have data.
If Not rs.EOF Then
' Transfer result.
Sheets(sheetNewName).Range("A1").CopyFromRecordset rs
' Close the recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
' -------------- End of SQL --------------------------------------------
End If
i = i + 1
Loop
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
'-----------------------------------------------
' Turn on automatic updating
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Application.StatusBar = "Finished"
'-----------------------------------------------
End Sub
【问题讨论】:
标签: sql excel vba import adodb