【问题标题】:How to export a table in access to CSV with dot in field names through VBA?如何通过 VBA 导出表以访问 CSV 中的字段名称中的点?
【发布时间】:2014-01-08 01:48:52
【问题描述】:

我需要在导出 CSV 的字段名称中添加点。我无法在访问表字段中包含点,并且我找不到通过 VBA 更新 CSV 字段名称的方法。有什么建议吗?谢谢。

【问题讨论】:

  • CSV 是纯文本格式,因此您应该可以使用 VBA 重写标题行。你试过了吗?

标签: vba ms-access csv


【解决方案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."

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多