簡體   English   中英

如何通過VBA導出字段名稱中帶有點的CSV訪問表?

[英]How to export a table in access to CSV with dot in field names through VBA?

我需要在導出CSV的字段名稱中加點。 我不能在訪問表字段中包含點,也找不到通過VBA更新CSV字段名稱的方法。 有什么建議嗎? 謝謝。

您所描述的非常簡單。 對於[表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."

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM