使用vba从Access数据库中提取excel

问题描述 投票:0回答:1

基本上,我想在VBA中的查询中从访问基础中提取一列。我的示例代码如下,没有找到错误,但唯一有效的是它只是打开excel文件,应该复制来自访问的数据。

'Set db = OpenDatabase("\\location\names.mdb")
Set rs = db.OpenRecordset("select first_name from customerinfo " _
& "where datehired between #" & (DTPicker1) & "#  and #" & (DTPicker2) & "# ;")


If rs.RecordCount <> 0 Then

Dim x As Integer
Dim count As Integer
Dim PATH, file As String
PATH =("\\location\Extracted Data.xlsm")
file = Right$(PATH, Len(PATH) - InStrRev(PATH, "\"))
Workbooks.Open PATH
Workbooks(file).Activate

count = rs.RecordCount
For x = 2 To count
Workbooks(file).Sheets("extracted").Range("a" & x) = rs.Fields("first_name")

Next
End If'

我应该在我的Excel中复制3个结果。有人可以帮助我找到我的代码中似乎缺少的东西吗? :(

excel vba ms-access access-vba
1个回答
0
投票

首先,你在动态集中完全加载记录集之前使用.RecordCount。这可能会返回1,因为只有1个记录已经加载,使你的代码跳过For x = 2 To count(因为那是for x=2 to 1

其次,你实际上并没有移动记录集。

一个更好的方法(除了我可能错过的其他错误):

x = 2
Do While Not rs.EOF 'While not at the end of the recordset
    Workbooks(file).Sheets("extracted").Range("a" & x) = rs.Fields("first_name")
    x = x + 1
    rs.MoveNext 'Move to next record
Loop
© www.soinside.com 2019 - 2024. All rights reserved.