读取逗号分隔的文本文件

时间:2020-02-24 14:53:07

标签: vba ms-access

我正在尝试使用Access vba读取文本文件,并希望在引号之间返回值。



示例文本文件(adm_settings.txt)

email_subject| "This is my email subject"
email_body| "This is my email body. 

so many thing 

to 

write"

我需要调用下面的函数,并返回引号之间所有要求的设置。

Public Function getAdmSettingBAK(sSetting As String) As String

    Dim bFoundIt As Boolean
    Dim sDir As String
    Dim sFile As String
    Dim sLineString As String
    Dim sField() As String

    sDir = CurrentProject.Path & "\"
    sFile = "adm_settings.txt"

    If (Dir(sDir & sFile) = "") Then
        MsgBox "can't find settings file: " & sDir & sFile
        Exit Function
    Else
        'Debug.Print "using settings file: " & sDir; sFile
    End If


    Open sDir & sFile For Input As #1

    Do Until EOF(1)
        Line Input #1, sLineString
        'Debug.Print sLineString
        sField = Split(sLineString, "|")

        'Debug.Print "setting: " & sField(0) & " == value: " & sField(1)
        If sField(0) = sSetting Then
            bFoundIt = True
            getAdmSetting = sField(1)
        End If

    Loop

    Close #1

    If Not bFoundIt Then
        MsgBox "can't find setting " & sSetting
    End If

 MsgBox "This is the string: " & getAdmSetting
ExitMe:

End Function


如果我删除引号,该功能将起作用,但只会返回第一行(不包括换行符等。

1 个答案:

答案 0 :(得分:1)

这是您可以执行此操作的另一种方法(我已经使用您的数据对其进行了测试):

Public Function getAdmSettingBAK(sSetting As String) As String
    Dim fso, MyFile
    Dim iStart As Integer, iEnd As Integer
    Dim response As String, myRecord As String
    Dim sField() As String
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set MyFile = fso.OpenTextFile(CurrentProject.path & "\adm_settings.txt", 1)
    response = MyFile.ReadAll

    iStart = InStr(response, sSetting) ' find the sSetting string
    If iStart = 0 Then Exit Function  ' sSetting does not exists
    myRecord = Mid(response, iStart) ' cut off string from start to sSetting

    iStart = InStr(myRecord, "|") ' find the 1st pipe
    iEnd = InStr(Mid(myRecord, iStart + 1), "|")  ' find the 2nd pipe

    If iEnd = 0 Then iEnd = Len(myRecord)  ' there is no more records in file

    myRecord = Mid(myRecord, 1, iStart + iEnd - 1)  ' cutt off up to the end of the 2nd record
    iEnd = InStrRev(myRecord, vbCrLf)  ' find the last new line character
    If iEnd > 0 Then  ' this is not the last record in file
        myRecord = Mid(myRecord, 1, iEnd - 1) ' get the whole record
    End If

    sField = Split(myRecord, "|")
    getAdmSettingBAK= Trim(sField(1))

End Function