excel-vba – 尝试在VBA中存储文本文件行

问候,我希望能帮助找出如何将文本文件的每一行作为字符串存储到VBA程序中.我想修改其中一个字符串,然后将它们全部重新组合在一起,但不知道如何读取文本文件并以智能方式将每一行存储为单独的变量.感谢您的任何帮助,您可以提供!
如果您不想添加引用,可以使用直接的vba代码.

以下面的文件wordlist.txt为例:

realize
empty
theorize
line
socialize
here
analyze

以下代码使用两种方法来执行(一种比另一种更常见):

Option Explicit

Sub main()
    Dim sFileName As String
    Dim sMergedLineArray() As String
    Dim sTextToFind As String
    Dim sReplacementText As String
    Dim sOutputFile As String
    Const MY_DELIMITER = "|"

    sFileName = "C:\deleteme\wordlist.txt"

    sMergedLineArray = ReadFileIntoArray(sFileName)

    sTextToFind = "ze"
    sReplacementText = "se"

    'Loop through each value in the array and make a change if you need to
    Dim x As Integer
    For x = 0 To UBound(sMergedLineArray)
        If InStr(1, sMergedLineArray(x), sTextToFind, vbTextCompare) > 0 Then
            sMergedLineArray(x) = Replace(sMergedLineArray(x), sTextToFind, sReplacementText, 1, -1, vbTextCompare)
        End If
    Next x

    sOutputFile = "C:\deleteme\UK_Version.txt"
    If Not SpitFileOut(sOutputFile, sMergedLineArray) Then
        MsgBox "It didn't work :("
    End If


    'OR...put it all together, make a mass change and split it back out (this seems unlikely, but throwing it in there anyway)
    sTextToFind = "se"
    sReplacementText = "ze"
    Dim sBigString As String
    Dim sNewArray As Variant
    sBigString = Join(sMergedLineArray, MY_DELIMITER)
    sBigString = Replace(sBigString, sTextToFind, sReplacementText, 1, -1, vbTextCompare)

    sNewArray = Split(sBigString, MY_DELIMITER, -1, vbTextCompare)

    sOutputFile = "C:\deleteme\American_Version.txt"
    If Not SpitFileOut(sOutputFile, sNewArray) Then
        MsgBox "It didn't work"
    End If

    MsgBox "Finished!"

End Sub


Function ReadFileIntoArray(sFileName As String) As String()
    Dim sText As String
    Dim sLocalArray() As String
    Dim iFileNum As Integer
    Dim iLineCount As Integer

    iFileNum = FreeFile

    Open sFileName For Input As #iFileNum
    Do Until EOF(iFileNum)
        Input #iFileNum, sText
        ReDim Preserve sLocalArray(iLineCount)
        sLocalArray(iLineCount) = sText
        iLineCount = iLineCount + 1
    Loop

    Close #iFileNum

    ReadFileIntoArray = sLocalArray


End Function


Function SpitFileOut(sFileName As String, sMyArray As Variant) As Boolean
    Dim iFileNum As Integer
    Dim iCounter As Integer

    SpitFileOut = False

    iFileNum = FreeFile

    Open sFileName For Output As #iFileNum
        For iCounter = 0 To UBound(sMyArray)
            Print #iFileNum, sMyArray(iCounter)
        Next
    Close #iFileNum


    SpitFileOut = True
End Function

如果你运行main sub,你最终会得到两个文件:

> UK_Version.txt:这是第一种方法的结果
> American_Version.txt:这是第二个结果

VBA的第一课,年轻的Padawan;吸收它,学习并更改你的登录名:P

https://stackoverflow.com/questions/5797835/trying-to-store-text-file-rows-in-vba

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:excel-vba – 尝试在VBA中存储文本文件行