[英]How to export a table in access to CSV with dot in field names through VBA?
I need to have dot in the field names of the export CSV. 我需要在导出CSV的字段名称中加点。 I cannot include dot in the access table field, and I cannot find a way to update the CSV field name by VBA.
我不能在访问表字段中包含点,也找不到通过VBA更新CSV字段名称的方法。 Any suggestion?
有什么建议吗? Thanks.
谢谢。
What you describe is quite straightforward. 您所描述的非常简单。 For sample data in [Table1]
对于[表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.
the following VBA code 以下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
produces this CSV file 产生这个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."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.