Читать текстовый файл с разделителями-запятыми - PullRequest
0 голосов
/ 24 февраля 2020

Я пытаюсь прочитать текстовый файл, используя 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


функция работает, если я удалю кавычки, но вернет только первую строку (не включить разрывы строк и т. д. c.

1 Ответ

1 голос
/ 25 февраля 2020

Это другой вариант, как вы можете это сделать (я проверил это с вашими данными):

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...