[英]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. 我认为循环应该是有效的,因为工作表名称是1,2,3,4,5。 So I was thinking of making a for loop, but im really stuck.
所以我在考虑制作一个for循环,但我真的陷入困境。
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". 工作表的名称是一个字符串,通过使用整数,它将调用第一个工作表而不是名为“1”的工作表。 So changing it to cstr(i) it will change the 1 to "1".
因此将其更改为cstr(i)它会将1更改为“1”。
I simply combined your two routines and qualified your workbooks/worksheets. 我简单地将您的两个例程组合在一起,并对您的工作簿/工作表进行了限定。
thisworkbook
is assumed to be test
. 假设该工作
thisworkbook
是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.