个人宏不在不同的工作簿中循环

时间:2017-01-30 17:11:16

标签: excel vba loops for-loop

我的问题是在工作簿中循环遍历几个工作表。

我需要在我的个人工作簿中保存宏,但是如果我这样做,它会循环遍历同一个工作表,直到达到工作表计数。

如果我将代码移动到当前工作簿,它可以很好地工作。我已经研究过编写宏来将模块从个人工作簿复制到当前工作簿,但是对于其他用户,这个模块将被保存在另一个只在后台打开以运行模块的工作簿中。

当代码保存到我的个人工作簿中的模块,或者只是保存在后台打开的另一个工作簿中时,如何让它循环遍历另一个工作簿中的所有工作表?

以下代码:

Route::get('{className}/{id}', function($className, $id) {
  return call_user_func_array($className.'::handle', [$id]);
}

2 个答案:

答案 0 :(得分:2)

此代码的逻辑略有不同,但如果有效则尝试:

   Sub WorksheetLoop()

      ' Loop Through Worksheets, Add Totals

    Dim LastRow As Long
    Dim ws As Worksheet
    Dim starting_ws As Worksheet
    Dim path As String
    Dim WorkingFile As Workbook
      ' Select the file you will manipulate to surely be in the correct WB.
    path = Application.GetOpenFilename(FileFilter:="Excel Files (*.*), *.*", Title:="Please select a file you want to modify")
    Workbooks.Open path
    Set WorkingFile = ActiveWorkbook

      For Each ws In WorkingFile.Worksheets
      ws.Rows("1:6").Insert Shift:=xlDown

      'Rest of the code
      Next
 End Sub

答案 1 :(得分:0)

以下是工作代码,现在将其与最初发布的代码进行比较。

再次感谢Vinnie和Gordon!

Sub Step_3_Add_Subtotals()

' Loop Through Worksheets, Add Totals

Dim LastRow As Long
Dim ws As Worksheet
Dim starting_ws As Worksheet
Set starting_ws = ActiveSheet

' Loop Sum Formula Through All Worksheets


For Each ws In ActiveWorkbook.Worksheets
ws.Activate

  'Now my code, the do something

'Insert new blank rows

Rows("1:6").Select
Selection.Insert Shift:=xlDown

'Copy current headers, paste them in K3:Q3
Range("K7:Q7").Select
Selection.Copy
Range("K3").Select
ActiveSheet.Paste


'Got to next worksheet, and now it does!

Next

starting_ws.Activate

End Sub