将列表框值从 mc 访问表单导出到保持相同列数的 excel 文件

Exporting listbox values from mc access form to excel file maintaining the same number of columns

所以我设法创建了一个代码来将列表框值复制并粘贴到新创建的 excel 文件中。 问题是,我将它们全部连接起来并用逗号分隔。它工作正常,但由于它是如何导出的,所以我必须使用 Excel 文本到列功能来按我想要的方式放置数据。

代码如下:

Private Sub button_Export_AMAT_Click()

Dim i As Integer
Dim n As Integer

Dim strLine As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("\yvavm301\Commun\CF_GDC\base de dados a trabalhar\AM_AT.csv", True)

    For i = 0 To Me.List_AM_AT.ListCount - 1

            For n = 0 To Me.List_AM_AT.ColumnCount - 1

             strLine = strLine & """" & Me.List_AM_AT.Column(n, i) & ""","
           
            Next n

        strLine = Left(strLine, Len(strLine) - 1)
        a.writeline (strLine)
        strLine = ""

    Next i

    MsgBox "Your file is exported"
    
End Sub

我的问题是:是否可以为 table 导出一个赞,即。具有相同数量的列并用正确的值填充它们?

必须在此处进行更改(见下文),对吗?

strLine = strLine & """" & Me.List_AM_AT.Column(n, i) & ""","
a.writeline (strLine)

我试过以下方法,但没有成功:

strLine = Me.List_AM_AT.Column(n, i)    
a.cells(i,n).writeline (strLine)

有人知道该怎么做吗?

正如我在评论中所说,您可以在代码中创建一个 Excel 文件并将值写入该文件。现在您使用您的代码创建一个文本文件,这会导致您在 post(文本助手等)

中描述的问题
Private Sub button_Export_AMAT_Click()

    Dim i As Integer
    Dim n As Integer
    
    ' You might need to add a reference to Excel if your host application is Access
    ' Extra/Reference and select Microsoft Excel Object Library
    Dim xl As Excel.Application
    Set xl = New Excel.Application

    Dim wkb As Workbook
    Set wkb = xl.Workbooks.Add
    
    Dim wks As Worksheet
    Set wks = wkb.Sheets(1)

    'Dim strLine As String
    'Set fs = CreateObject("Scripting.FileSystemObject")
    'Set a = fs.CreateTextFile("\yvavm301\Commun\CF_GDC\base de dados a trabalhar\AM_AT.csv", True)

    For i = 0 To Me.List_AM_AT.ListCount - 1

        For n = 0 To Me.List_AM_AT.ColumnCount - 1
            
            wks.Cells(i + 1, n + 1).Value = Me.List_AM_AT.Column(n, i)
            'strLine = strLine & """" & Me.List_AM_AT.Column(n, i) & ""","
        Next n
'
'        strLine = Left(strLine, Len(strLine) - 1)
'        a.writeline (strLine)
'        strLine = ""

    Next i
    
    wkb.SaveAs "D:\TMP\EXPORT.XLSX"  ' Adjust accordingly
    wkb.Close False
    xl.Quit
    MsgBox "Your file is exported"
    
End Sub