I have several folders that I want this code to edit inbetween start and finish. The part of the code that recycles the search in a different folder doesn't see any *.csv when Folder2 replaces Folder1 for SubFolder, but if the initial condition for SubFolder at the start is changed manually by me from "Folder1" to "Folder2" it will detect *.csv files in that folder now. It also detects *.csv in "Folder1" and "Folder3" when they are the initial condition for SubFolder. I did check as recommended in other questions and couldn't find any missing "\" in this code
Global Myfile, MyFolder, NewFile, SubFolder As String
Sub SpecificFileTypeInSpecificFolders()
'
SubFolder = "Folder1"
MyFolder = "C:\xxxxxx\" & SubFolder
Myfile = Dir(MyFolder & "\*.csv")
MsgBox SubFolder
MsgBox Myfile
Do While Myfile <> ""
MsgBox SubFolder
MsgBox Myfile
Myfile = Dir
If Myfile = "" Then
If SubFolder = "Folder2" Then 'several more folders like this
SubFolder = "Folder3"
End If
If SubFolder = "Folder1" Then
SubFolder = "Folder2"
End If
End If
MsgBox SubFolder
MsgBox Myfile
Loop
End Sub
Changing the value of the
SubFolder
variable after the line of codeMyFolder = "C:\xxxxxx\" & SubFolder
has no effect on theMyFolder
variable. When you concatenate string variables using the&
operator you are taking the value of theSubFolder
variable and appending it to theC:\xxxxxx\
text and putting the result into the value of theMyFolder
variable.If you want to search a known list of folders, create an array of the folders and then loop through the array.
Avoid using
Globals
- best practice is to declare variables with the minimum scope required. In VBA when you declare several variables on the same line you must specify the variable type of each one because otherwise they get defined asVariant
. So in your line of code onlySubFolder
is defined as a string:Instead use:
Personally, I prefer to keep each variable declaration on a separate line.
This code should run ok: