Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用vba从Access数据库提取到excel_Excel_Ms Access_Vba - Fatal编程技术网

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

使用vba从Access数据库提取到excel,excel,ms-access,vba,Excel,Ms Access,Vba,基本上,我想根据VBA中的查询从access中提取一列。 下面是我的示例代码,没有发现错误,但唯一有效的方法是打开excel文件,然后复制access中的数据 'Set db = OpenDatabase("\\location\names.mdb") Set rs = db.OpenRecordset("select first_name from customerinfo " _ & "where datehired between #" & (DTPicker1) &

基本上,我想根据VBA中的查询从access中提取一列。 下面是我的示例代码,没有发现错误,但唯一有效的方法是打开excel文件,然后复制access中的数据

'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'
我应该有3个结果要复制到我的excel中。有人能帮我找到代码中缺少的内容吗

例如,在将记录集完全加载到动态集之前,您正在使用.RecordCount。这可能会返回1,因为只加载了1条记录,使代码跳过x=2进行计数,因为这是x=2对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

谢谢@erik,你的想法真的很管用,我只是加了几行,让它适合我的需要。谢谢