提问人:ThisIsMe 提问时间:9/19/2023 最后编辑:ThisIsMe 更新时间:10/15/2023 访问量:24
将所选数据从 Access 导出到 Excel
exporting selected data from access to excel
问:
我有一个很大的访问数据库,有许多列和超过 2000 行。有时我需要将数据导出到 excel 以发送信件等,但每次都是不同的数据,例如:
大多数时候,我不需要所有的列,比如当我发送信件时,我只需要姓名和地址,而不是所有信息。
我并不总是需要所有数据,比如只有一个城市的客户,或者高于购买金额等。
有没有办法制作一个简单的表单或其他东西,其中包含选择要导出的列和数据的选项?
我尝试(使用 AI 引擎),它给了我以下代码以在导出按钮上使用:
Private Sub ExportButton_Click()
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
Dim strSQL As String
Dim rs As Object
' Create a new Excel application
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
' Create a new workbook and worksheet in Excel
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)
' Get the selected column name
Dim selectedColumn As String
selectedColumn = Forms("export").Controls("SelectedColumnListBox").Column(0, Forms("export").Controls("SelectedColumnListBox").ListIndex)
'MsgBox Forms("export").Controls("SelectedColumnListBox").Value
' Get the selected specific data
Dim selectedData As String
selectedData = Me.SelectedDataListBox.Value
' Build the SQL query to retrieve the data
If selectedData = "" Then
' If selectedData is null, return all options
strSQL = "SELECT " & selectedColumn & " FROM full"
Else
' If selectedData is not null, filter by the selected value
strSQL = "SELECT " & selectedColumn & " FROM full WHERE " & selectedColumn & " = '" & selectedData & "' OR " & selectedColumn & " IS NULL"
End If
' Execute the query
Set rs = CurrentDb.OpenRecordset(strSQL)
' Check if the recordset is empty
If rs.EOF Then
MsgBox "No records found."
Else
' Export the data to Excel
xlSheet.Range("A1").CopyFromRecordset rs
End If
' Clean up
rs.Close
Set rs = Nothing
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
但它一直向我显示错误 94,这些值为 null
答:
0赞
Gustav
10/15/2023
#1
它这么说是有原因的。因此,请尝试使用 Nz:
selectedData = Nz(Me!SelectedDataListBox.Value)
评论