Excel VBA Allow user to select an already open workbook and attach variables to selected workbook - vba

With Excel 2013 VBA, I am familiar with setting the value of a Workbook variable with:
Set oWBSource = Workbooks.Open(strFileToOpen) 'Works well.
In my situation though, sometimes the Workbook is already open on the desktop. I am trying to find a more elegant way to "select" that spreadsheet and then attach my variable to that workbook to operate on. The code is running on a separate "master" spreadsheet.
Currently, I am asking the user if the file is already open. If so, then:
Dim rng As Range
Set rng = Application.InputBox("Select any cell on workbook to operate on.", "Click Workbook Cell", Type:=8) 'Stops code and allows user to select a cell on an open spreadsheet
Dim sTest As String 'variable used to test.
sTest = ActiveCell.Value 'Testing to see what value code is seeing.
sTest = ActiveWorkbook.Name 'Testing to see what value code is seeing
Set oWBSource = Workbooks(ActiveWorkbook.Name) 'Works if selected Workbook is maximized and minimized.
If I run the above code and when it runs the inputbox, if I click one cell on the spreadsheet I want the code to operate on and allow the code to continue, the variables still reference the Workbook where the code resides rather than the "selected" workbook. If, while selecting one cell, I also maximize and minimize the spreadsheet (basically Activate it) and then click a cell and allow the code to continue, the active spreadsheet is set and it seems to work. I realize the cell reference is doing nothing. But the pause allows me to "Activate" the desired spreadsheet.
I am looking for a more elegant way to handle attaching my code to an already open spreadsheet. My current solution is clunky. Isn't there a way to have the user select the open spreadsheet and then have my code "act" on that spreadsheet?
I know this is a weird question. Be kind rating it please??!!

If I understand correctly what you're trying to do, just use the rng to resolve the selected Workbook:
Set oWBSource = rng.Parent.Parent
rng.Parent is the Worksheet a Range is a part of, and the .Parent of a Worksheet is its Workbook.

Related

How to run a macro from a different workbook in a shared network?

So, I've done a lot of research on this and my code isn't working still. As per the title, the problem is this:
I pull a data report off of a website, this report is downloaded as an .xlsx file. I created a macro on the ribbon so I when I click it, it will then open another workbook and run that macro. The code I'm using is as below:
Option Explicit
Sub NotHardAtAll()
Dim ws As Worksheet,
Dim wb As Workbook
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Workbooks.Open Filename:="C:\Users\a0c27n\Desktop\Projects\incident_extended_report1.xlsm"
'With Sheets("Sheet4").Activate '*Not sure if this is enter code here
necessary...at all*
Application.Run "!ADDHMKRFID"
'End With
End Sub
I've tried putting the path before the macro (i.e. Application.Run"'incident_extended_report1.xlsm!ADDHMKRFID") but it doesn't work either*
I'm aware, at least form the research I've done, that I should be able to just use the 'Application.Run' Method, however I couldn't get it to access the correct sheet.
When I run the Macro, it pulls a Run-time error '1004' error, a '400', or the it pulls the most is: "Cannot run the macro '!ADDHMKRFID'. The macro may not be available in this workbook or all macros may be disable."
The file that I'm trying to pull the macro from is below:
Workbook name: incident_extended_report1.xlsm
Worksheet name: Sheet4 (TEST MACRO)
Macro Name:
Sub ADDHMKRFID()
End Sub
I understand that the C:\ is not a shared network, the one I will be working out of will be the S:\, however I'm not sure how much information I can post due to confidentiality.
Please ask for any clarification or questions you may have. I've been stuck for a bit and am not sure what I'm doing wrong. Thanks in advance!
The string you need to pass to Application.Run depends on whether the workbook containing the macro is active, and if it isn't, the filename of the macro-containing workbook (IE: what's in the workbook.Name property).
if the macro is supposed to be run while the data report workbook is active, you want:
dim wb_data as Workbook: set wb_data = ActiveWorkbook
dim ws_data as Worksheet: set ws_data = ActiveSheet
dim wb_macro as Workbook
set wb_macro = Workbooks.Open(Filename:="C:\Users\a0c27n\Desktop\Projects\incident_extended_report1.xlsm")
ws_data.Activate
Application.Run wb_macro.Name & "!ADDHMKRFID"
This will guarantee that the correct string is supplied, even if you change the name of the macro file.
Otherwise, if the macro workbook is supposed to be active, skip activating the data worksheet, as the last opened workbook will be active by default, then use "ADDHMKRFID" as your string. Note that the "!" is missing. You need that only if you are specifying a macro in another workbook. It's the same kind of notation used when referring to data in other worksheets.
First of all, I solved my own problem. I would, however, be grateful if someone might explain to me why it worked the way it did.
I saved the original macro on the shared network, but I had to save it as a module (in this case Module1). I also saved the 2nd macro (to run the original one) in a different workbook (though it shouldn't matter, as long it is not a .xlsx file).
The Code I wrote was:
Sub Test() 'Name doesn't matter
Application.Run "'S:\xxxx\xxxx\xxxx\incident_extended_report.xlsm'!module1.ADDHMKRFID"
End Sub
Then I saved this macro to the ribbon so I could run it on the data report.xlsx file I have to download. Now, anytime I want to run the original macro, I just click the Test Macro, and it'll run the other one!
I'm guessing if you want to close the other workbook that you opened, you can just add a
Workbooks (“S:\xxxx\xxxx\xxxx\incident_extended_report.xlsm").Close Savechanges:=False
Good Luck!

Removing links from copied worksheet

What I want to do
I want a code in my workbook (wbDestination) that opens another workbook (wbBosOriginal) and copies an entire sheet as values (wbBosOriginal has a lot of code in it, in modules and in the worksheet in question, and I do not want this code because it references stuff in wbB that doesn't exist in wbDestination). I have had great problems pasting as values, because it will not paste columns and rows that are currently hidden. So this is why I decided to import the whole sheet instead.
What I tried and what's wrong with it
Here is a block of code I used to copy the worksheet in the destination workbook, in the last index position. The problem with it is that some links still exist to the old workbook (Formulas, validation lists, conditionnal formatting). I have deleted all these links but STILL when I paste the sheet successfully, save and reopen, I have an error saying some content is unreadable. I believe there are still some elements linked to the old workbook.
Set wbBosOriginal = Workbooks.Open(strChosenPath, ReadOnly:=True)
With wbBosOriginal.Sheets("BOS")
.Visible = True
'Pastes the ws in last position in wbDestination
.Copy after:=wbDestination.Sheets(wbDestination.Worksheets.Count)
Set wsNewBos = Worksheets(Worksheets.Count)
'Deletes VBA code in the copied sheet
ThisWorkbook.VBProject.VBComponents.Item(wsNewBos.CodeName).CodeModule.DeleteLines 1, _
ThisWorkbook.VBProject.VBComponents.Item(wsNewBos.CodeName).CodeModule.CountOfLines
End With
The worksheet is successfully pasted with no code in it, with everything else it had previously. I then remove all formulas, conditionnal formatting, and validation lists. Even after removing those as well, I still get an error when opening the workbook.
My question
Apart from conditional formatting, validation lists, VBA code, and formulas linking a worksheet that was pasted to a new workbook, what other elements could cause the workbook from opening in repair mode every time due to existing links to the old workbook?
If my question is not clear, comment and I will clarify.
Dealing directly with VBE seems a bit heavy-handed to me. If your code is manipulating several workbooks, I would put the code in an add-in and not have it in any workbook. (Technically *.xlam addins are workbooks, but when I say "workbook" I mean normal *.xls, *.xlsx, *.xlsm, etc.)
That said, if you're just copying cell values (which may be formulas) between different workbooks, you shouldn't have any dependencies other than cell references, named ranges, and user-defined functions in the original workbook. I would make sure there are none of those. Please also share how you are ensuring your formulas do not have broken references.
If the issue you are having is caused by trying to avoid hidden columns and rows not allowing pastevalues, why not unhide the rows and columns and then copy only the values to the new book?
Just cycle through each of the sheets in the original book and use the method .UsedRange.Hidden = False. As far as I am aware, this should unhide every cell on the sheet and allow you to do the original pastevalues calls
This works fast and smooth (it's harder to delete ALL the data Imo):
Sub tests()
Dim AllRange As Range: Set AllRange = ActiveSheet.UsedRange
Dim ItemRange As Range
Dim myWbDestination As Workbook: Set myWbDestination = ThisWorkbook
Dim SheetDestination As String: SheetDestination = ("Sheet2")
For Each ItemRange In AllRange
With myWbDestination.Sheets(SheetDestination)
.Range(ItemRange.Address) = ItemRange.Value
End With
Next ItemRange
End Sub
Repair mode can be triggered by many factors, you would need to post the code you are getting to look for an explanation, it would be like asking why vba may broke

Reference an excel sheet from another workbook without copying the sheet

Im wondering if it's possible to reference an excel sheet from another work book without making a copy of that sheet?
The situation : I have some very large worksheets filled with various data, but i don't want to keep a copy of them open in my workbooks because while each workbook uses the same data source, they're slightly different.
I have a vba routine that takes this data and creates input files for other codes, vba expects this data to be available on the defined sheet names.
Is it possible to make either excel or vba to know that when i request worksheet("Example_1") it instead knows that i mean example_1 from a different workbook?
Thanks
Yes, it is possible.
You need to add those lines to your code:
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set wkb = Excel.Workbooks("name_of_workbook.xlsx")
Set wks = wkb.Worksheets("Example_1")
Now, every time you want to refer to a range from this other workbook, you need to add wks. before, i.e.:
'Printing value in cell.
wks.Range("A1") = "x"
'Selecting range.
call wks.Range(wks.Cells(1,1), wks.Cells(2,2)).Select
=SUM('C:\test\[test.xlsx]sheet_name'!A1:A25)
is an example of a formula which references sheet sheet_name in workbook C:\test\text.xlsx.
Note that when the other workbook is opened, the formula automatically changes to
=SUM([test.xlsx]sheet_name!A1:A25)
and then when it is closed, the formula will change back.

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!
p.s. hoping im clear.

Vb.net Updating excel formula with references to other workbooks

I am trying to update some formulas from one workbook, to another workbook. Everything is working great until I run into a formula that has a reference to another workbook. For example a formula like this =IF(ISERROR(W!Var1),0,W!Var2) It will prompt me to open this workbook, I am assuming so that it can evaluate the formula. So my question is this. Is there a way for me to handle these situations on the fly, so if there is a workbook reference needed it will prompt me and then save it to memory? Because if I have more than one cell that contains these formulas it will prompt me to open the referenced workbook for every cell that contains the link. Alternatively, is there a way that I can just push my formula into the cell without having excel evaluate it?
So in my code I have this line which works for any value that doesn't contain a workbook reference. TheRange.RefersToRange.FormulaR1C1 = RangeFormula
Any help is greatly appreciated.
I understand that you refer to Worksheets (each of the "tabs" in a given Excel file), the Workbook is the whole file. The popping-up message appears when the referred Worksheet cannot be found. Example: range.Value = "=sheet5!A3" (in a Workbook having just "sheet1", "sheet2" and "sheet3"). If you want to avoid this message (although bear in mind that the Worksheet is not there and thus the calculations will be wrong anyway), you can write:
excelApp.DisplayAlerts = False
Where excelApp is the Excel.Application you are currently using.