2

我正在尝试根据数字列表在目录中查找文件。每个文件都以 6 位数字开头,但可以以随机字母结尾。- 所以我设法编写了一个脚本,它只比较文件名的前六个字母。此外,我只想复制 .pdf 和 .dxf 文件——这就是为什么我还要检查文件类型。

只是为了使它更复杂,文件的“源文件夹”是不同的。它由数字的前 3 位数字和 2 个“_”组成。例如。

C:\文件\258__\258956.pdf

这可以通过将前三位数字和 __ 添加到源路径来轻松解决。(但尚未实施)

问题是我的脚本确实无限运行,因为它永远不会离开循环。它也只检查文件列表中的第一个数字。

在这个问题之前我真的在互联网上搜索过。另外,我想为 stackoverflow 社区提供支持,因为直到现在其他问题确实有帮助。

  • 我通常只在 vba (Excel) 中编写脚本,这就是我不熟悉 vbs 的原因。

在我的文件列表的一部分之后,它定义了必须找到哪些文件

   127287
   257391
   257605
   258956
   261648
   261880
   261886
   262284

这是我已经拥有的脚本

    dim fso, folder, sourcefolder, destfolder, searchname1,fileList

    set fso = createobject("scripting.filesystemobject") 
    sourcefolder = "C:\Users\Admin\Desktop\Source"
    destfolder = "C:\Users\Admin\Desktop\output\"
    inputFile = "C:\Users\Admin\Desktop\filelist.txt" 
    Set fileList = fso.OpenTextFile(inputFile, forReading) 

    ' Read line after line the next number which has to be found
    searchname1 = fileList.ReadLine() 

    ' But stop reading lines if the end is reached
    Do until fileList.AtEndOfStream 

    set folder = fso.getfolder(sourcefolder)  

    'Compare each file
    for each file in folder.files
        wholefilename = fso.getbasename(file)
        filename = left(wholefilename,6)
        extension = LCase(fso.getextensionName(file))

    'first compare the name with the list ¦ then check the fileextenstion 
        if (filename = searchname1) and  ((extension = "pdf") or (extension ="dxf")) then

    'it both statements are true, copy the file to the destinationfolder "Ouptut"
fso.copyfile sourcefolder & "\" & file.name, destfolder
else          
end if

    next
    Loop

我的问题的解决方案可能非常简单,但我真的被卡住了。所以任何帮助表示赞赏。总结一下,我的大问题是,脚本永远不会退出循环。但我不知道如何以及何时结束它,经过 10'000 次循环将是一个愚蠢的解决方案。

4

1 回答 1

2

您需要像这样在 Do 循环中移动 ReadLine:

Dim fso, folder, sourcefolder, destfolder, searchname1, fileList
Set fso = CreateObject("scripting.filesystemobject")
sourcefolder = "C:\Users\Admin\Desktop\Source"
destfolder = "C:\Users\Admin\Desktop\output\"
inputFile = "C:\Users\Admin\Desktop\filelist.txt"
Set fileList = fso.OpenTextFile(inputFile, forReading)

' But stop reading lines if the end is reached
Do Until fileList.AtEndOfStream
   ' Read line after line the next number which has to be found
   searchname1 = fileList.ReadLine()
   Set folder = fso.getfolder(sourcefolder)

   'Compare each file
   For Each File In folder.Files
       wholefilename = fso.getbasename(File)
       FileName = Left(wholefilename, 6)
       extension = LCase(fso.getextensionName(File))

       'first compare the name with the list ¦ then check the fileextenstion
       If (FileName = searchname1) And ((extension = "pdf") Or (extension = "dxf")) Then
          'it both statements are true, copy the file to the destinationfolder "Ouptut"
          fso.copyfile sourcefolder & "\" & File.name, destfolder
       End If
   Next
Loop
于 2017-06-29T20:15:02.223 回答