0

我正在尝试使用 VBScript 计算文本文件中的行数。对于具有固定名称的文本文件,我已经成功地做到了这一点。EG: "C:\Orig\sample.txt" 但是,我们的文件名每天都在变化,EG: "C:\Orig\sample* todaysdate *.txt"

我一直在寻找一种“读取”具有变量名的文件的方法并且没有运气。

到目前为止,我所拥有的固定文件名是:

Dim oFso, oReg, sData, lCount, linesum 
Const ForReading = 1, sPath = "C:\Orig\sample.txt" 
Set oReg = New RegExp 
Set oFso = CreateObject("Scripting.FileSystemObject") 
sData = oFso.OpenTextFile(sPath, ForReading).ReadAll 
With oReg 
    .Global = True 
    .Pattern = "\r\n" 'vbCrLf 
    lCount = .Execute(sData).Count + 1

End With 
WScript.Echo("The total number of lines including the header is " & lCount) 
Set oFso = Nothing 
Set oReg = Nothing

这工作得很好,但我只是找不到变量文件名的正确语法。

如果有任何帮助,我要查询的文件将是包含文件夹中的唯一文件。

有人可以提供任何帮助吗?非常感谢。


我现在尝试了以下方法:

Dim objFso, objReg, sData, lCount 
Const ForReading = 1 
sPath = "C:\Orig" 

Set objFso = CreateObject("Scripting.FileSystemObject")  
Set objFolder = objFso.GetFolder(sPath) 
For Each objFile in objFolder.Files 
    Set objReg = New RegExp  
    sData = objFso.OpenTextFile(sPath, ForReading).ReadAll
    With objReg  
        .Global = True  
        .Pattern = "\r\n" 'vbCrLf  
        lCount = .Execute(sData).Count + 1 

    End With  
    WScript.Echo("The total number of lines including the header is " & lCount)  
    Set objFso = Nothing  
    Set objReg = Nothing
    Set objFolder = Nothing
    set sData = Nothing
Next 

但在第 9 行,我收到“权限被拒绝”错误。我已经检查了文件夹权限和文件权限,并且我拥有完整的权限。

有人有什么想法吗?

提前致谢。

4

1 回答 1

0

而是循环浏览文件夹中的文件。无需直接命名文件。

Dim oFso, oReg, sData, lCount, linesum 
Const ForReading = 1
sPath = "C:\Orig\sample\"

Set oFso = CreateObject("Scripting.FileSystemObject") 
Set objFolder = objFso.GetFolder(sPath)
For Each objFile in objFolder.Files
    Set oReg = New RegExp 
    sData = oFso.OpenTextFile(sPath, ForReading).ReadAll 
    With oReg 
        .Global = True 
        .Pattern = "\r\n" 'vbCrLf 
        lCount = .Execute(sData).Count + 1

    End With 
    WScript.Echo("The total number of lines including the header is " & lCount) 
    Set oFso = Nothing 
    Set oReg = Nothing
Next
于 2012-08-20T17:00:28.143 回答