简体   繁体   中英

Excel Macro - Run Against Another Workbook

Good Morning All,

I'm just trying to understand how to run a macro that is in one workbook but apply the macro procedure/changes into another workbook that is open.

What I am trying to achieve is one workbook is say the Template that will always be open. I have a macro in that Template file that works through a directory looking for xlsm files and opens them one at a time. What I want to do is when the workbook is opened another macro is called in the Template file which updates connection string details in the other open workbook.

I have the macros ready and they work, but I want to run them against another workbook without having to copy the code into it.

Is this at all possible?

Thanks in advance.

Make a variable to store your workbook, then use it to refer to it. Something like this:

'place this at the top of the module so that the variable can be used by all macros
Private wb As Workbook

'place this in your "browse and open" macro in place right after you open a workbook
Set wb = ActiveWorkbook

'now you can do whatever you want by referring to wb
wb.Worksheets("Sheet 1").Range("A1") = "Cell A1"
wb.Worksheets("Sheet 2").Range("C3").EntireRow.Delete
wb.Close

You could also continue referring to ActiveWorkbook , but you have to make sure that it actually remains active all the time you want to work on it. If in the meantime you want to do something on your template workbook, you can refer to it as ThisWorkbook .

Sub h()

'ask for row number >>

k = InputBox("witch row?")

' you now define the worksheet >>

Sheet2.Select

'now you see that in this case i used a selected cell as point of reference>>

Sheet2.Range("a" & k).EntireRow.Delete

End Sub

In MS EXCEL Sheet1, go to "Insert tab", to "shapes",>>

select a rounded cornered box, add a text to it so its intuitive,>>

change the colors of text and background, then :>>

select the shape you created with the mouse with a "right click">>

and from the list that appears select "Assing Macro", and select macro "h"

if all goes to theese indications, we have the next step >>

if u click it it runns the sub. and therefor you will be presented with a inputbox, where you specify the row number you want to be deleted.


there you go!

ps hoping im clear.

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