简体   繁体   中英

Using a For Loop to run Macros on multiple sheets with ordered names like 1,2,3,4

I have a created a Macro that copies data from a sheet from a different workbook->"data" onto the current workbook->"test"

Sub copy_data()

Windows("data.xlsx").Activate
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Windows("test.xlsm").Activate
Range("A1").Select
ActiveSheet.Paste
End Sub

I want to make this macro run for multiple sheets which are in the "data" workbook.

I believe a loop should be efficient as the sheet names are 1, 2, 3, 4 ,5. So I was thinking of making a for loop, but im really stuck.

What I've done so far is shown below:

Sub Loopsheets()
Dim wks As Worksheet
Dim i As Integer
Dim iStart As Integer
Dim iEnd As Integer

iStart = 1
iEnd = 5

If iStart > 0 And iEnd > 0 And iEnd > iStart Then
  For i = iStart To iEnd
   Set wks = ThisWorkbook.Worksheets(i)
   Application.run "copy_data"
  Next i
End If
End Sub

This is untested but should work:

Sub copy_data(ws As Worksheet)

Dim dwb As Workbook
Dim dws As Worksheet

Set dwb = Workbooks("data.xlsx")
Set dws = dwb.Worksheets(1)

With dws
    .Range(.Cells(1, 1), .Cells(1, 1).End(xlDown).End(xlToRight)).copy ws.Range("A1")
End With

End Sub



Sub Loopsheets()
Dim wks As Worksheet
Dim i As Integer
Dim iStart As Integer
Dim iEnd As Integer

iStart = 1
iEnd = 5

If iStart > 0 And iEnd > 0 And iEnd > iStart Then
  For i = iStart To iEnd
   Set wks = ThisWorkbook.Worksheets(CStr(i))
   copy_data wks
  Next i
End If
End Sub

The name of the sheet is a string, by using an integer it will be calling the first sheet not sheet named "1". So changing it to cstr(i) it will change the 1 to "1".

I simply combined your two routines and qualified your workbooks/worksheets. thisworkbook is assumed to be test .

Sub Loopsheets()
Dim wks As Worksheet
Dim ws As Workbook
Dim i As Integer
Dim iStart As Integer
Dim iEnd As Integer

iStart = 1
iEnd = 5
Set wb = Workbooks("data")

For i = iStart To iEnd

    Set wks = wb.Worksheets(cstr(i)) 'edited per Scott
    With wks
        .Range("A1").Select
        .Range(Selection, Selection.End(xlDown)).Select
        .Range(Selection, Selection.End(xlToRight)).Select
        Selection.Copy
    End With

    ThisWorkbook.Range("A1").Select
    Selection.Paste

Next i

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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