下面是实现将Access VBA中的表格导出为CSV文件的示例代码:
Public Sub ExportTableToCSV(tableName As String, filePath As String)
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim fs As Object
Dim file As Object
Dim field As DAO.Field
Dim headerStr As String
Dim rowStr As String
Dim i As Integer
'打开数据库
Set db = CurrentDb()
'获取指定表的记录集
Set rs = db.OpenRecordset(tableName, dbOpenSnapshot)
'创建文件系统对象
Set fs = CreateObject("Scripting.FileSystemObject")
'创建CSV文件
Set file = fs.CreateTextFile(filePath, True, True)
'写表头
For Each field In rs.Fields
headerStr = headerStr & "," & field.Name
Next field
headerStr = Mid(headerStr, 2)
file.WriteLine headerStr
'写记录
Do Until rs.EOF
rowStr = ""
For i = 0 To rs.Fields.Count - 1
rowStr = rowStr & "," & rs.Fields(i).Value
Next i
rowStr = Mid(rowStr, 2)
file.WriteLine rowStr
rs.MoveNext
Loop
'关闭文件和记录集
file.Close
rs.Close
Set file = Nothing
Set rs = Nothing
MsgBox "导出成功!"
End Sub
这个代码中的ExportTableToCSV过程接受两个参数:tableName和filePath。tableName是要导出的表的名称,filePath是要保存CSV文件的路径和文件名。代码首先打开指定表,然后创建一个CSV文件,并在CSV文件的第一行写入表头。接下来,代码循环遍历记录集,每个记录写入CSV文件的新行中。最后,关闭文件和记录集。
你可以通过在Access VBA中调用这个过程来导出指定的表格为CSV文件。例如,可以通过以下方式将名为“students”的表格导出到名为“students.csv”的文件中:
ExportTableToCSV "students", "C:\exported\students.csv"