我需要在导出CSV的字段名称中加点。我无法在访问表字段中包含点,我找不到通过VBA更新CSV字段名称的方法。有什么建议吗?感谢。
答案 0 :(得分:1)
您所描述的内容非常简单。对于[表1]
中的样本数据ID text column int column datetime column "other" column
-- ----------- ---------- ------------------- ------------------
1 foo 3 1991-11-21 01:23:45 This is a test.
2 bar 9 2013-12-31 23:59:59 ...and so is this.
以下VBA代码
Option Compare Database
Option Explicit
Public Sub dotCsvExport(TableName As String, FileSpec As String)
Dim cdb As DAO.Database, tbd As DAO.TableDef, fld As DAO.Field
Dim s As String, line As String, tempFileSpec As String
Dim fso As Object ' FileSystemObject
Dim fOut As Object ' TextStream
Dim fTemp As Object ' TextStream
Const TemporaryFolder = 2
Const ForReading = 1
Const ForWriting = 2
Set cdb = CurrentDb
Set fso = CreateObject("Scripting.FileSystemObject") ' New FileSystemObject
tempFileSpec = fso.GetSpecialFolder(TemporaryFolder) & fso.GetTempName
' export just the data to a temporary file
DoCmd.TransferText _
TransferType:=acExportDelim, _
TableName:=TableName, _
FileName:=tempFileSpec, _
HasFieldNames:=False
Set fTemp = fso.OpenTextFile(tempFileSpec, ForReading, False)
Set fOut = fso.OpenTextFile(FileSpec, ForWriting, True)
' build the CSV header line, replacing " " with "." in field names
Set tbd = cdb.TableDefs(TableName)
line = ""
For Each fld In tbd.Fields
s = fld.Name
s = Replace(s, " ", ".", 1, -1, vbBinaryCompare)
s = Replace(s, """", """""", 1, -1, vbBinaryCompare)
If Len(line) > 0 Then
line = line & ","
End If
line = line & """" & s & """"
Next
Set fld = Nothing
Set tbd = Nothing
' write the CSV header line to the output file
fOut.WriteLine line
' append the actual data from the temporary file
fOut.Write fTemp.ReadAll
fOut.Close
Set fOut = Nothing
fTemp.Close
Set fTemp = Nothing
Kill tempFileSpec
Set fso = Nothing
Set cdb = Nothing
End Sub
生成此CSV文件
"ID","text.column","int.column","datetime.column","""other"".column"
1,"foo",3,1991-11-21 01:23:45,"This is a test."
2,"bar",9,2013-12-31 23:59:59,"...and so is this."