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

时间:2019-03-26 15:15:11

标签: arrays 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”在文件中出现多次,那么我只想从上次出现在文件中时开始抓取它。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您需要做的所有事情,因为要反向读取数组(从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

答案 1 :(得分:0)

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)

输出

  

其他方面
  小计2
  还有其他
  小计4
  还有其他东西

     

子类别4