在DataSet Excel VBA中查找最后一行

时间:2014-03-06 11:10:27

标签: excel excel-vba vba

我正在尝试导入数据以查找数据集的最后一行,并将SQL Server中的数据行粘贴到数据集末尾的空白行中。

这是我的代码,但是在运行代码时,它会导入数据,但总是在最后一行,而不是最后一行之后的下一个空行

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

我需要做些什么才能把它做好?

1 个答案:

答案 0 :(得分:0)

我发现这是对我所寻找的更简单的答案。

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