在下面的代码中,我能够循环遍历 9 个(文件数量会有所不同)txt 文件并抓取这些文本文件中的特定行。我获取的值是一个数量值,并且总是列在同一位置。我在计算这些数量的总和时遇到了一些困难。
当前代码:
Set oFile2 = FSO.OpenTextFile(File.path, ForReading)
i = 0
'process text files
Do While oFile2.AtEndOfStream <> true
text = oFile2.ReadLine
'WSCript.Echo text
ReDim Preserve SSheet(i)
SSheet(i) = text
i=i+1
Loop
oFile2.Close
Set oFile2 = Nothing
Set objFSO = Nothing
'find row and strips down quantity
Dim QtyTrim
QtyTrim = Mid((SSheet(30)),6,4)
'convert quantity to int
Dim QtyInt
QtyInt = CInt(QtyTrim)
WSCript.echo QtyInt
Main
) 的文件的过程 (FOLDER_PATH
),并针对具有给定扩展名 (FILE_EXTENSION
) 的每个文件,调用检索字符串 ( GetQuantity
),由函数常量定义,将字符串转换为整数,并将整数传递回过程,在过程中将其添加到变量 (FoundString
)。最后,显示一个消息框,其中包含结果总数。重点关注Total
GetQuantity
Empty
Option Explicit
Main
Sub Main()
Const FOLDER_PATH = "C:\Test"
Const FILE_EXTENSION = "txt"
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(FOLDER_PATH) Then
MsgBox "The path """ & FOLDER_PATH & """ doesn't exist!", vbExclamation
Exit Sub
End If
Dim fsoFile, Quantity, Total, FilesFound
For Each fsoFile In fso.GetFolder(FOLDER_PATH).Files
If StrComp(fso.GetExtensionName(fsoFile), FILE_EXTENSION, _
vbTextCompare) = 0 Then
FilesFound = FilesFound + 1
Quantity = GetQuantity(fso, fsoFile.Path)
If Not IsEmpty(Quantity) Then
Total = Total + Quantity
Quantity = Empty ' reset for the next iteration
End If
End If
Next
If IsEmpty(FilesFound) Then
MsgBox "No " & FILE_EXTENSION & "-files found!", vbExclamation
Exit Sub
End If
If IsEmpty(Total) Then
MsgBox "No quantities found!", vbExclamation
Else
MsgBox "Total: " & Total, vbInformation
End If
End Sub