简体   繁体   中英

Run Same VBA Macro Code for more than one Worksheet

My following code runs perfectly, it is just copying and pasting data from one workbook to another workbook called 'summary workbook'. Every workbook corresponds to a gage station in which I am extracting the same cells from all the workbooks onto a 'summary workbook' that contains all the data. I wanted to know if there is a way to repeat the same code for each gage workbook, so I wouldn't have to manually change it? I know I would have to change the workbook it is copying it from as well, or would I have to change that manually as well?

Additional info:

The workbook that I am copying is called "run_10296500.xlsm", and within that workbook I am taking out the data in the sheet called "dashboard". The "summary workbook" is the active workbook, and sheet1 is in this workbook.

The code I have is as follows:

Sub Hungry4Gages()

Dim x As Workbook

Dim y As Workbook

'## Open both workbooks first:

Set y = ActiveWorkbook


 Dim LastRow As Long

    For i = 1 To 50
        If Cells(i, 1).Value = "Grand Total" Then
            Line = i
            Range("A" & i + 1 & ":CS50").Select
            Selection.Clear
            Exit For
        End If
    Next

'FALL

[Class1!E6].Formula = "='C:\Users\dguitron\Documents\Belize and Sam Project\Class 1\[run_10296500.xlsm]dashboard'!E17"
[Class1!E6] = [Class1!E6].Value        

[Class1!E7].Formula = "='C:\Users\dguitron\Documents\Belize and Sam Project\Class 1\[run_10296500.xlsm]dashboard'!E18"
[Class1!E7] = [Class1!E7].Value         

[Class1!E8].Formula = "='C:\Users\dguitron\Documents\Belize and Sam Project\Class 1\[run_10296500.xlsm]dashboard'!E19"
[Class1!E8] = [Class1!E8].Value         


End Sub

Unless I am mistaken only the end part of your code seems to relate to your question. In which case you simply need to change the workbook name in each reference as follows.

[Class1!E6].Formula = "='C:\Users\dguitron\Documents\Belize and Sam Project\Class 1\[run_10296500.xlsm]dashboard'!E17"
[Class1!E6] = [Class1!E6].Value        

[Class1!E7].Formula = "='C:\Users\dguitron\Documents\Belize and Sam Project\Class 1\[run_10296501.xlsm]dashboard'!E17"
[Class1!E7] = [Class1!E7].Value         

[Class1!E8].Formula = "='C:\Users\dguitron\Documents\Belize and Sam Project\Class 1\[run_10296502.xlsm]dashboard'!E17"
[Class1!E8] = [Class1!E8].Value         

Obviously I don't know the name of your other workbooks so I've just incrementes the last digit. If you want to make this a bit slicker then you could create an array of workbook names or use a counter with a For loop to cut down on the repitition but we would need to know more about your workbook naming convention to assist any further.

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