简体   繁体   中英

Find Last Row in DataSet Excel VBA

I'm trying to get my data import to find the last row of my dataset and paste the row of data from SQL Server into the blank row at the end of the data set.

This is my code I have, but when running the code it will import the data but always on the last row, not the next blank row after the last row

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

I imagine that I have put something in wrong around

Sheet1.Range("B5").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveCell.Offset(1, 0).CopyFromRecordset rs

What do I need to do to put it right?

我发现这是对所要查找内容的简单得多的答案。

Range("A1").End(xlDown).Offset(1, 0).Select

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM