简体   繁体   English

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

[英]Looping through file extensions, excel vba

I am using an Array of File extensions and looping through a folder of workbooks. 我正在使用一个文件扩展数组并循环遍历工作簿的文件夹。 The code is naming Sheet(1).name="MyName" 代码命名为Sheet(1).name =“MyName”

I notice that even though "*.xlsm" is not in the array, it is still opening and naming the sheet. 我注意到即使"*.xlsm"不在数组中,它仍然打开并命名工作表。

在此输入图像描述

Here's the code. 这是代码。 Can anybody see if they get the same problem and are able to solve it. 任何人都可以看到他们是否遇到同样的问题并且能够解决它。

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

The legacy short (8.3) file name for HELLO.ABCD would look something like ABCDEF~1.ABC - see the extension is truncated to 3 characters. HELLO.ABCD的旧版短(8.3)文件名看起来像ABCDEF~1.ABC - 请参阅扩展名截断为3个字符。

In your case GET.XLSM would be ABCDEF~1.XLS and this 8.3 form is also matched by the Win32 API FindFirstFile (which is what Dir() calls under the hood) when you specify *.XLS 在你的情况下,当你指定*.XLS时, GET.XLSM将是ABCDEF~1.XLS并且这个8.3表单也匹配 Win32 API FindFirstFile (这是Dir()在引擎盖下调用的)。

Just filter out the exceptions in you loop with 只需过滤掉循环中的异常

If Not UCase$(MyFile) Like "*.XLSM" Then 
    ....

While Alex has solved your query, I have updated your code below to 虽然Alex已经解决了您的查询,但我已将下面的代码更新为

  • ensure it handles all excel file types 确保它处理所有excel文件类型
  • handle the sheet name already existing (else your code will error out) 处理已存在的工作表名称(否则您的代码将出错)
  • cleanup and properly use variables 清理并正确使用变量
  • restore events at close 在收盘时恢复活动

     Sub LoopThroughFolder() Dim Wb As Workbook Dim MyFile As String Dim MyDir As String Dim StrFile As String MyDir = "C:\\temp\\" ChDir MyDir With Application .ScreenUpdating = False .DisplayAlerts = False End With StrFile = "*.xls*" MyFile = Dir(MyDir & StrFile) Do While Len(MyFile) > 0 If MyFile Like "*.xlsx" Or MyFile Like "*.xlx" Then Set Wb = Workbooks.Open(MyFile) On Error Resume Next Wb.Sheets(1).Name = "MySheet" On Error GoTo 0 Wb.Save Wb.Close False End If MyFile = Dir() Loop With Application .ScreenUpdating = True .DisplayAlerts = True End With End Sub 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM