0
我試圖讓我的數據導入找到我的數據集的最後一行,並將數據從SQL Server行粘貼到數據集末尾的空行。在DataSet Excel中查找最後一行VBA
這是我的代碼我有,但在運行代碼時,它會導入數據,但總是在最後一排,而不是最後一行之後的下一個空白行上
Sub RunImport()
On Error GoTo Err:
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=MyServer; " & _
"Initial Catalog=Mydb;" & _
"User ID=User;" & _
"Password=Pwd;" & _
"Trusted_Connection=No"
Set cnn = New ADODB.Connection
Application.ScreenUpdating = False
cnn.Open cnnstr
Set rs = New ADODB.Recordset
sQRY = "SELECT * FROM MyTable"
rs.CursorLocation = adUseClient
rs.Open sQRY, cnn, adOpenDynamic, adLockOptimistic, adCmdText
Application.ScreenUpdating = False
Sheet1.Range("B5").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveCell.Offset(1, 0).CopyFromRecordset rs
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
Exit Sub
Err:
MsgBox "The following error has occured-" & vbCrLf & vbCrLf & VBA.Error, vbCritical, "MySpreadsheet"
MsgBox VBA.Err
End Sub
我想,我已經把東西在錯誤的地方
Sheet1.Range("B5").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveCell.Offset(1, 0).CopyFromRecordset rs
我需要做些什麼才能把它放正確?
閱讀:[**如何確定最後使用的行/列**](http://stackoverflow.com/questions/11169445/error-finding-last-used-cell-in-vba/ 11169920#11169920) –
使用調試器,在這一行放置一個斷點:'Range(Selection,Selection.End(xlDown))。選擇',然後按步進入,看看在Excel中會發生什麼。也許它只是選擇單元格,並沒有激活它,也許它選擇從底行開始的第二行,在這種情況下,如果它始終如一地執行,你可以說'ActiveCell.Offset(2,0).CopyFromRecordset rs',是的,閱讀simco's關於查找最後一行的鏈接 – user1759942