通过文件扩展名循环,excel vba

Dav*_*cel 2 excel vba excel-vba

我正在使用一个文件扩展数组并循环遍历工作簿的文件夹.代码命名为Sheet(1).name ="MyName"

我注意到即使"*.xlsm"不在数组中,它仍然打开并命名表单.

在此输入图像描述

这是代码.任何人都可以看到他们是否遇到同样的问题并且能够解决它.

Sub LoopThroughFolder()

    Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook
    Dim Rws As Long, Rng As Range
    Dim fExt, ext
    Set Wb = ThisWorkbook
    'change the address to suite
    MyDir = "C:\TestWorkBookLoop\"
    ChDir MyDir
    Application.ScreenUpdating = 0
    Application.DisplayAlerts = 0
    fExt = Array("*.xlsx", "*.xls")    'file extensions, set the file extensions of the files to move

    For Each ext In fExt    'loop through file extensions
        MyFile = Dir(MyDir & ext)


        Do While MyFile <> ""
            Workbooks.Open (MyFile)
            Sheets(1).Name = "MySheet"

            With ActiveWorkbook
                .Save
                .Close
            End With

            MyFile = Dir()
        Loop
    Next ext
End Sub
Run Code Online (Sandbox Code Playgroud)

Ale*_* K. 7

遗留的短(8.3)文件名HELLO.ABCD看起来像ABCDEF~1.ABC- 看扩展名被截断为3个字符.

你的情况GET.XLSMABCDEF~1.XLS,这8.3的形式也匹配由Win32 API FindFirstFile(这是什么Dir()引擎盖下调用)当您指定*.XLS

只需过滤掉循环中的异常

If Not UCase$(MyFile) Like "*.XLSM" Then 
    ....
Run Code Online (Sandbox Code Playgroud)