【问题标题】:specific file types in specific folders with vba使用 vba 的特定文件夹中的特定文件类型
【发布时间】:2015-06-27 11:21:51
【问题描述】:

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

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

【问题讨论】:

    标签: vba file directory


    【解决方案1】:

    在代码行MyFolder = "C:\xxxxxx\" &amp; SubFolder之后更改SubFolder变量的值对MyFolder变量没有影响。当您使用&amp; 运算符连接字符串变量时,您将获取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
    

    【讨论】:

    • 感谢您的帮助,因为这可能是我在 VBA 中所做的第三件事。我正在寻找一个矩阵版本,其中“folderNames”也在一个数组中。
    猜你喜欢
    • 2017-07-07
    • 2016-10-02
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2016-02-16
    • 1970-01-01
    相关资源
    最近更新 更多