每个人都很棒的代码。它工作得很好而且很快。我添加了一行,用于处理传入的表名包含空格的情况。
Tablename = IIf(Left(Tablename, 1) = "[", Tablename, "[" & Tablename & "]")
我的整个过程的版本(有一个更改):
Public Sub ExportToCSV(Tablename As String, _
strFile As String, _
Optional strQualifier As String = vbNullString, _
Optional strDelimiter As String = ",", _
Optional FieldNames As Boolean = False)
'References: Microsoft Access 11.0 Object Library, Microsoft DAO 3.6 Object Library
'Set references by Clicking Tools and Then References in the Code View window
'
' Exports a table to a text file.
' Accepts
' Tablename: Name of the Target Table or Query
' strFile: Path and Filename to Export the table to
' strQualifier: specifies text qualifier (typically a double-quote)
' strDelimiter: String Value defaults to comma: ,
' FieldNames: True or False
'
'USAGE: ExportToCSV TableName, strFile, Chr$(34), ",", True
On Error GoTo errhandler
Dim intOpenFile As Integer
Dim strSQL As String, strCSV As String
Dim fld As DAO.Field
Tablename = IIf(Left(Tablename, 1) = "[", Tablename, "[" & Tablename & "]")
'Close any open files, not that we expect any
Reset
'Grab Next Free File Number
intOpenFile = FreeFile
'Open our file for work
Open strFile For Output Access Write As #intOpenFile
'Write the contents of the table to the file
'Open the source
strSQL = "SELECT * FROM " & Tablename
With CurrentDb.OpenRecordset(strSQL, dbOpenSnapshot)
'Check if we need Field Names
If FieldNames Then
For Each fld In .Fields
strCSV = strCSV & strDelimiter & strQualifier & fld.Name & strQualifier
Next fld
' remove leading delimiter
strCSV = Mid$(strCSV, Len(strDelimiter) + 1)
'Write to File
Print #intOpenFile, strCSV
End If
'Write records to the CSV
Do Until .EOF
strCSV = ""
For Each fld In .Fields
If fld.Type = dbText Or fld.Type = dbMemo Then
strCSV = strCSV & strDelimiter & strQualifier & fld.Value & strQualifier
Else
strCSV = strCSV & strDelimiter & fld.Value
End If
Next fld
' remove leading delimiter
strCSV = Mid$(strCSV, Len(strDelimiter) + 1)
'Eliminate Back to back strQualifiers
If Len(strQualifier) > 0 Then
strCSV = Replace(strCSV, strQualifier & strQualifier, "")
End If
'Write to File
Print #intOpenFile, strCSV
.MoveNext
Loop
.Close
End With
ExitHere:
'Close the file
Close #intOpenFile
Exit Sub
errhandler:
With Err
MsgBox "Error " & .Number & vbCrLf & .Description, _
vbOKOnly Or vbCritical, "ExportToCSV"
End With
Resume ExitHere
End Sub