简体   繁体   English

在所有工作表上运行我的宏

[英]Running my macro on all worksheets

I have to prepare a short Macro. 我必须准备一个简短的Macro。 I multiple worksheets in a workbook and I wrote a macro to import a range from a different workbook, but I want my macro to loop over all worksheets. 我在一个工作簿中有多个工作表,并且编写了一个宏以从其他工作簿中导入范围,但是我希望我的宏可以遍历所有工作表。 I read a lot about it but still I think I am missing some basic knowledge on . 我阅读了很多有关它的内容,但我仍然认为我缺少有关一些基本知识。 Could someone please help me to put this macro in a loop? 有人可以帮我把这个宏放在一个循环中吗?

Sub AddHeader()
    current = ActiveWorkbook.Name
    Range("A1:C96").Select
    Selection.Cut Destination:=Range("A55:C150")
    Windows("MIP_Ordering_Header.xlsx").Activate
    Range("A1:H54").Select
    Selection.Copy
    Windows(current).Activate
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
    SkipBlanks:=False, Transpose:=False
    ActiveSheet.Paste
    Cells(53, 1).Value2 = "Plate Name:" & ActiveSheet.Name
End Sub

I would do something similar to below. 我会做类似下面的事情。 Copy the range first, and then loop through the sheets in the active workbook: 首先复制范围,然后遍历活动工作簿中的工作表:

Sub AddHeader() 子AddHeader()

Dim WS_Count As Integer
Dim I As Integer

'first get the data to copy
Windows("MIP_Ordering_Header.xlsx").Activate
Range("A1:H54").Select
Selection.Copy
ActiveWorkbook.Close

'get all the active sheets
WS_Count = ActiveWorkbook.Worksheets.Count

' Begin the loop.
For I = 1 To WS_Count
    'refer to the curent workbook using the "I" variable
    ActiveWorkbook.Worksheets(I).Range("A1").Select
    'the rest of your code...
Next End Sub

Edit: How to copy paste with variables: 编辑:如何复制粘贴变量:

Sub CopyPaste()

Dim src1 As Variant
Dim src2 As Variant

src1 = Sheets(1).Range("A1:A2").Value
src2 = Sheets(1).Range("A4:A5").Value

Sheets(1).Range("B1:B2").Value = src1
Sheets(1).Range("B4:B5").Value = src2 End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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