【问题标题】:Looping a code through a folder of workbooks with VBA?使用 VBA 在工作簿文件夹中循环代码?
【发布时间】:2014-03-28 04:13:55
【问题描述】:

我有一个文件夹,里面有许多格式相同的 excel 文件。我修改了以下代码来确定日期并重新格式化,其中“i”根据第 2 列的最后一行确定范围内的单元格数。

Sub Test()
   Dim i As Long
   i = Sheet1.Cells(Rows.Count, 2).End(xlUp).Row
   With Range("K3:K" & i)
        .Formula = "=DATE(A3,G3,H3)"
        .NumberFormat = "ddmmmyyyy"
   End With  
End Sub

我想对我文件夹中的所有工作簿执行此代码。我在stackoverflow上发现了以下问题:

Code for looping through all excel files in a specified folder, and pulling data from specific cells

它不会循环遍历我的所有文件,仅适用于我打开的第一个 excel 文件。 如何在文件夹中的所有工作簿中循环这段代码?以下是我目前所拥有的。

Sub Test()
Dim lCount As Long
Dim wbResults As Workbook
Dim wbCodeBook As Workbook
Dim i As Long

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

On Error Resume Next
    Set wbCodeBook = ThisWorkbook
        With Application.FileSearch
            .NewSearch

            .LookIn = "C:\Test"
            .FileType = msoFileTypeExcelWorkbooks

                If .Execute > 0 Then
                    For lCount = 1 To .FoundFiles.Count

                        Set wbResults = Workbooks.Open(Filename:=.FoundFiles(lCount), UpdateLinks:=0)

   i = wbResults.Worksheets("Sheet1").Cells(wbResults.Worksheets("Sheet1").Rows.Count, 2).End(xlUp).Row
   With wbResults.Worksheets("Sheet1").Range("K3:K" & i)
        .Formula = "=DATE(A3,G3,H3)"
        .NumberFormat = "ddmmmyyyy"
   End With

                        wbResults.Close SaveChanges:=False
                    Next lCount
                End If
        End With
On Error GoTo 0
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub

【问题讨论】:

  • 从您的链接中,您可以看到这一行:Set wbResults = Workbooks.Open(...。接下来你的步骤是i = wbResults.Worksheets("Sheet1").Cells(wbResults.Worksheets("Sheet1").Rows.Count, 2).End(xlUp).RowWith wbResults.Worksheets("Sheet1").Range("K3:K" & i)
  • 我已尝试进行更改,但它确实对我的工作簿进行了任何更改。工作簿的文件名作为工作表名称,我将其中 3 个更改为 sheet1 以查看是否是问题所在,但它仍然不起作用。我已附上我在主要问题中输入的代码。
  • 可能是因为wbResults.Close SaveChanges:=False - 你关闭了工作簿而不保存更改:)
  • 这是有道理的。它似乎根本没有运行代码。我打开了其中一个工作簿,运行时没有发生任何更改。顺便感谢您的帮助。
  • 尝试删除On Error Resume Next 声明。你会得到一些错误吗?

标签: vba loops excel


【解决方案1】:

Application.FileSearch 不受 Excel 2007 及更高版本的支持。试试这个代码 (code for looping through files in a folder was taken from @mehow's site)

Sub PrintFilesNames()
    Dim file As String
    Dim wbResults As Workbook
    Dim i As Long
    Dim myPath As String

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    myPath = "D:\" ' note, path ends with back slash

    file = Dir$(myPath & "*.xls*")

    While (Len(file) > 0)
        Set wbResults = Workbooks.Open(Filename:=myPath & file, UpdateLinks:=0)

        With wbResults.Worksheets(Split(file, ".")(0))
            i = .Cells(.Rows.Count, 2).End(xlUp).Row
            With .Range("K3:K" & i)
                 .Formula = "=DATE(A3,G3,H3)"
                 .NumberFormat = "ddmmmyyyy"
            End With
        End With

        wbResults.Close SaveChanges:=True
        'get next file
        file = Dir
    Wend

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

【讨论】:

  • 我收到一条错误消息:使用 wbResults.Worksheets("Sheet1")。错误说 wbResults.Worksheets("Sheet1") = 我还想注意我正在使用 csv 文件,我在代码中将 xls 更改为 csv,这会影响它吗?
  • 啊我不知道,那完全是另一个问题。谢谢你的回答。
  • 实际上它会在保存后存储公式的结果。顺便说一句,我刚刚用 csv 文件对其进行了测试——它对我有用,没有任何错误。
  • 嗯,是的,我将文件转换为 xls,但在 With wbResults.Worksheets("Sheet1") 上仍然出现错误,其中显示 =
  • 太棒了!非常感谢您的专业知识,再次感谢您!
【解决方案2】:

这是受到 Chris Newman 在电子表格大师上的帖子的启发
复制并粘贴整个代码块,用您要执行的特定代码替换一行“wb.Worksheets(1).Range("A1:Z1").Interior.Color = RGB(51, 98, 174)”每个工作簿。

Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

'----------------------------------------------------------
'----------------------------------------------------------
'Here is where action code goes, what is going to be performed on each workbook
    'Change First Worksheet's Background Fill Blue
      wb.Worksheets(1).Range("A1:Z1").Interior.Color = RGB(51, 98, 174)
'----------------------------------------------------------
'----------------------------------------------------------

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 2018-05-27
    • 2016-11-25
    • 2018-06-04
    • 2015-08-06
    相关资源
    最近更新 更多