首页 > 解决方案 > 代码返回文件夹中的文件名列表,并使用 VBscript 在每个文件的第一行额外返回第 35 到第 40 位置的文本

问题描述

我正在尝试编写一个脚本,它将读取文件夹中的所有文件名并将它们列出,同时从第一行读取第 35 到第 45 个读取文本

样本文件数据

 {1:XXXXXXXXXXXXXX0000000000}{2:XXXXXXXXXXXXXXXXX}
{4:
:20:XXXXXXXXXXX
:21:XXXXXXXXXXX

我的代码

 Dim objFileSystem,wshShell,MainPath,fileCount,fileLIst,FiletoRead, objFile,strline, Newfile


Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Set NewFile = objFileSystem.CreateTextFile("c:\test\FileList.txt", True) 'Text file object
Set NewFile = objFileSystem.CreateTextFile("c:\test\FileList.txt", True) 'Text file object
MainPath="Path Location"


rem inputbox("Enter File Location here")
if objFileSystem.FolderExists(MainPath) then 
msgbox "control here 1"
FindFileRec MainPath
else
msgbox "Path " &  MainPath & "not found"
else if
 msgbox "completed"

Function FindFileRec(ThisFolder) 
Dim fileName,subFolderobj,subFolderList,Folderobj
Set Folderobj=objFileSystem.GetFolder(ThisFolder)
msgbox "control here 2"

For Each fileName In Folderobj.Files 
fileCount=fileCount+1 'update count
UpldateListInTextFile fileName.Name,NewFile
Next 'File
NewFile.Close()
End Function 

Function UpldateListInTextFile(sfile, NewFile) 
NewFile.WriteLine(sfile) 
End function

标签: excelvbscript

解决方案


请参阅OpenAsTextStream方法。

' VBScript
Const OUT_FILE = "C:\temp\FileList.txt"
Const PATH = "C:\temp\txt"

Dim objFSO, objOutFile, objFolder, objInFile, objTS, str, count
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutFile = objFSO.CreateTextFile(OUT_FILE, True)

If objFSO.FolderExists(PATH) then

    Set objFolder = objFSO.getFolder(PATH)
    For Each objInFile In objFolder.Files 
        set objTS = objInFile.OpenAsTextStream

        str = MID(objTS.readline,35,11)
        objOutFile.WriteLine objInFile.name & vbTab & str
        objTS.close

        count = count + 1
    Next

    objOutFile.close
    msgbox count & " lines written to " & OUT_FILE, vbInformation, "Finished"
Else
    msgbox "Path " & PATH & "not found", vbCritical
End If

推荐阅读