如何查找某个单词最后一次作为 VbScript 中的数组元素出现

How to find the last time a certain word appears as an element in an array in VbScript

我正在尝试查找数组 'arrFileLines' 中最后一次包含单词 "Subtot" 的行。目前它只是在每次出现时循环显示,而不是最后一次出现,我已经尝试了很多其他方法,但似乎无法解决它。

Sub FileSubTot

    Dim arrFileLines()
    Dim choice
    choice="SUBTOT"
    i = 0
    'opens txt file and makes each line an element in an array called arrFileLines
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile("C:\stuff\etc\etc...", 1)
    Do Until objFile.AtEndOfStream
     Redim Preserve arrFileLines(i)
     arrFileLines(i) = objFile.ReadLine
     i = i + 1
  Loop
  objFile.Close

  'iterates through the array looking for the word SUBTOT then grabs the subtotal value and compares to the (TTP)
For i = Ubound(arrFileLines) to LBound(arrFileLines) Step -1
    If InStr(arrFileLines(i), choice) <> 0 Then

    Log.Message "Found " & choice 
    Log.Message arrFileLines(i)
    Total=Split(arrFileLines(i),"     ",-1)
    Log.Message"TOTAL TO PAY: €"& Total(1)

    End If

Next

End Sub

如果 "Subtot" 在文件中出现多次,那么我只想从它最后一次出现在文件中时抓取它。非常感谢任何帮助。

您需要做的是,因为您正在向后读取数组(UBoundLBound),所以一旦找到您要查找的文本就退出循环,而不是而不是继续它。

Sub FileSubTot

    Dim arrFileLines()
    Dim choice
    choice="SUBTOT"
    i = 0
    'opens txt file and makes each line an element in an array called arrFileLines
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile("C:\stuff\etc\etc...", 1)
    Do Until objFile.AtEndOfStream
        Redim Preserve arrFileLines(i)
        arrFileLines(i) = objFile.ReadLine
        i = i + 1
    Loop
    objFile.Close

    'iterates through the array looking for the word SUBTOT then grabs the subtotal value and compares to the (TTP)
    For i = Ubound(arrFileLines) to LBound(arrFileLines) Step -1
        If InStr(arrFileLines(i), choice) <> 0 Then

            Log.Message "Found " & choice 
            Log.Message arrFileLines(i)
            Total=Split(arrFileLines(i),"     ",-1)
            Log.Message "TOTAL TO PAY: €"& Total(1)
            Exit For    ' This will exit the For Loop once the choice is found
        End If

    Next

End Sub

Filter 对这类事情很有用

' build a test string
dim a(4), i
for i = 0 to 4
    if i mod 2 = 1 then
        a(i) = "Subtot " & (i + 1)
    else
        a(i) = "Something else"
    end if
next

WScript.Echo Join(a, vbNewLine)

'reduce the array to a subset that just contains "subtot"
dim b: b = Filter(a, "subtot", true, vbTextCompare)
' use the last item in the array
i = UBound(b)
WScript.Echo b(i)

产出

Something else
Subtot 2
Something else
Subtot 4
Something else

Subtot 4