vba中特定文件夹中的特定文件类型

时间:2015-06-27 11:21:51

标签: vba file directory

我有几个文件夹,我希望此代码在开始和结束之间进行编辑。当Folder2替换Subfolder的Folder1时,在不同文件夹中循环搜索的代码部分看不到任何* .csv,但是如果我从“Folder1”到“Folder2”手动更改了开始时SubFolder的初始条件“它现在将检测该文件夹中的* .csv文件。当它们是SubFolder的初始条件时,它还检测“Folder1”和“Folder3”中的* .csv。我按照其他问题的建议进行了检查,但在此代码中找不到任何遗漏的“\”

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

1 个答案:

答案 0 :(得分:0)

在代码行SubFolder之后更改MyFolder = "C:\xxxxxx\" & SubFolder变量的值对MyFolder变量没有影响。当您使用&运算符连接字符串变量时,您将获取SubFolder变量的值并将其附加到C:\xxxxxx\文本并将结果放入MyFolder的值中变量。

如果要搜索已知的文件夹列表,请创建文件夹数组,然后循环遍历该数组。

避免使用Globals - 最佳做法是声明具有所需最小范围的变量。在VBA中,当您在同一行上声明多个变量时,必须指定每个变量的变量类型,否则它们将被定义为Variant。因此,在您的代码行中,只有SubFolder被定义为字符串:

Global Myfile, MyFolder, NewFile, SubFolder As String

改为使用:

Dim Myfile As String, MyFolder As String, NewFile As String, SubFolder As String

就个人而言,我更喜欢将每个变量声明放在一个单独的行上。

此代码应运行正常:

Sub SpecificFileTypeInSpecificFolders()
'
Dim myFile As String
Dim subFolder As Variant ' Must be variant to enable looping through the array
Dim folderNames As Variant
Dim mainFolder As String

    folderNames = Array("Folder1", "Folder2", "Folder3")
    mainFolder = "C:\xxxxxx\"

    For Each subFolder In folderNames
        MsgBox subFolder
        myFile = Dir(mainFolder & subFolder & "\*.csv")
        Do While myFile <> ""
            MsgBox myFile
            myFile = Dir
        Loop
    Next subFolder

End Sub