将选定的数据从Access导出到Excel

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

我有一个大型访问数据库,其中包含许多列和超过 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,这些值是空的

vba ms-access-2010 ms-access-2007
1个回答
0
投票

这么说是有原因的。所以尝试使用 Nz:

selectedData = Nz(Me!SelectedDataListBox.Value)
© www.soinside.com 2019 - 2024. All rights reserved.