Loop through folder, renaming files that meet specific criteria using VBA?

后端 未结 3 1968
自闭症患者
自闭症患者 2021-01-13 11:27

I am new to VBA (and have only a bit of training in java), but assembled this bit of code with the help of other posts here and have hit a wall.

I am trying to write

3条回答
  •  青春惊慌失措
    2021-01-13 11:34

    EDIT: See update below for an alternative solution.

    Your code has one major problem.. The last line before the Loop end is

       ...
       strfile = Dir(FILEPATH)  'This will always return the same filename
    
    Loop
    ...
    

    Here is what your code should be:

       ...
       strfile = Dir()  'This means: get the next file in the same folder
    
    Loop
    ...
    

    The fist time you call Dir(), you should specify a path to list files, so before you entered the loop, the line:

    strfile = Dir(FILEPATH)
    

    is good. The function will return the first file that matches the criteria in that folder. Once you have finished processing the file, and you want to move to the next file, you should call Dir() without specifying a parameter to indicate that you are interested in iterating to the next file.

    =======

    As an alternative solution, you can use the FileSystemObject class provided to VBA instead of creating an object by the operating system.

    First, add the "Microsoft Scripting Runtime" library by going to Tools->References->Microsoft Scripting Runtime

    enter image description here enter image description here

    In case, you did not see [Microsoft Scripting Runtime] listed, just browse to C:\windows\system32\scrrun.dll and that should do the same.

    Second, change your code to utilize the referenced library as follows:

    The following two lines:

    Dim fso As Object
    Set fso = VBA.CreateObject("Scripting.FileSystemObject")
    

    should be replaced by this single line:

    Dim fso As New FileSystemObject
    

    Now run your code. If you still face an error, at least this time, the error should have more details about its origin, unlike the generic one provided by the vague object from before.

提交回复
热议问题