复制并粘贴macros将更改名称的工作表
我正在尝试编写一个简单的macros来将数据从多个选项卡复制/粘贴到摘要选项卡中。 我的问题是,每个项目的示例标签将更改名称。 一旦我更改样本选项卡的名称,我的macros不再起作用。
有没有办法链接到工作表1,工作表2,工作表3等等,而不是每次都改变macros? 这里是我的一些代码,我有部分称为Sample或Sample(2)是需要改变每个项目。
提前致谢!
Sheets("Sample").Select Range("B15:B29").Select Selection.Copy Sheets("Data Summary").Select Range("B15").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Sheets("Sample (2)").Select Range("B15:B29").Select Application.CutCopyMode = False Selection.Copy Application.CutCopyMode = False Selection.Copy Sheets("Data Summary").Select Range("C15").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False
这不是最好的解决scheme,但它应该工作。 在运行macros之前,您需要确保您的汇总表是活动工作表。
Dim Summary As Worksheet: Set Summary = ActiveSheet Sheets("Sample").Select Range("B15:B29").Select Selection.Copy Summary.Select Range("B15").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Sheets("Sample (2)").Select Range("B15:B29").Select Application.CutCopyMode = False Selection.Copy Application.CutCopyMode = False Selection.Copy Summary.Select Range("C15").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False
这样做就是存储对当前工作表(摘要)的引用,并在复制数据时使用该引用调用工作表。
创build对工作表的引用( Dim Sheet As Worksheet
,然后为其分配Dim Sheet As Worksheet
)可让您访问该工作表上的数据,而不必先激活它,这有助于简化代码。 下面的例子应该和上面的例子有相同的结果。 汇总表在运行之前仍然需要激活。
Dim Summary As Worksheet: Set Summary = ActiveSheet Dim S1 As Worksheet: Set S1 = ThisWorkbook.Worksheets("Sample") Dim S2 As Worksheet: Set S2 = ThisWorkbook.Worksheets("Sample (2)") Application.ScreenUpdating = False S1.Range("B15:B29").Copy Summary.Range("B15").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False S2.Range("B15:B29").Copy Summary.Range("C15").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Application.ScreenUpdating = True
更多的例子! 这一个允许你预先定义你有多less“样本”表,而不必单独编码(希望没有testing过)
Dim Summary As Worksheet: Set Summary = ActiveSheet Dim Source As Worksheet Dim Index As Integer Dim Name As String Application.ScreenUpdating = False ' index represents the range of your sample sheets ' below my example assumes you have 5 For Index = 1 To 5 ' generate the name of the worksheet Name = "Sample" & IIf(Index > 1, " (" & Index & ")", "") Set Source = ThisWorkbook.Worksheets(Name) Source.Range("B15:B29").Copy ' using .Cells instead of .Range allows you to reference cells numerically ' so below its row 15 and the column changes depending on the index ' the +1 is there as your example starts at column B Summary.Cells(15, Index + 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Next Index Application.ScreenUpdating = True