VBA Select a sheet when the workbook is opened - vba

The following program doesn't work when I open my workbook. What are the possible reasons?
' Select the first sheet when the workbook is opened.
Private Sub Workbook_Open()
Sheet4.Select
Sheet4.Range("B1").Select
End Sub

If you hit alt+F11 to go to the VBA code editor. On the left side, under the file name you will see the different sheets, and whatever modules you might have in there. If you go under the ThisWorkbook module
and place your code there, it will automatically run when you start up the Excel File.

you are using the "Select" Method without an Activating a Sheet First!
Yes, when you have closed your workbook last time, the current sheet will remain in the memory index and when you will again open the same workbook, the pointer search for the most recent sheet used based on the index no.
'Here is the code
Private Sub Workbook_Open()
Sheet4.Activate
Sheet4.Select
Sheet4.Range("B1").Select
End Sub
using "Select Method" without Activating the Parent Object is a Crime. lol
Hope this will help you.

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!

unable to close opened excel workbook

I am building a excel file with commandbuttons, userforms etc. that contain links to other workbooks.
For the commandbuttons on my sheet I use the same code as for the commandbuttons in my userforms:
workbooks.open "path"
with the userform commandbuttons ater this the following is added
unload me
When I open a workbook via a userform I am unable to close it afterwards. I must activate my workbook first, then activate the opened one and then can I close it
I have tried putting "unload me" befor and after the "workbooks.open" but this doesn't change anything.
I also tried the followin, also didn't work:
unload me
dim wb as workbook
set wb = workbooks.open"pathname"
wb.activate
anyone any ideas?
Example of how it is now:
Someone needs to make a price calculation. they open the prices userform in my file. they click on the button "calculationfile". The calculationfile opens. they make there calculation and now they are finished in the calculationfile. So they want to close it by clicking on the cross. But they can't click the cross. then they switch to my file on the taskbar and then switch back to the calculation file. now they are able of clicking the cross
I dont understand why they can't click it the first time but they can click it after switching between mine and the openend workbook.
I suspect this is due to improper form handling and the "default instance" recreating itself after you unload it. If you don't create your own instance of the form before you show it, VBA will do all kinds of squirrelly things when you use it after it's unloaded.
If all you need to do is open a workbook and unload the form, *don't increment the workbook's reference count before you unload the form. Also, don't attempt to run any other code after you call Unload Me from the form. The code you posted should simply be:
Workbooks.Open "pathname"
Unload Me
Of course the calling code for the form isn't in the question, but it can likely be solved there as well.
Unload only affects a UserForm.
Try adding a reference to the open workbook and then closing it like so:
dim wb as Workbook
set wb = Workbooks.Open "pathname"
wb.activate
' do whatever with it while it's open
wb.Close
If whatever you are doing is not automated, you will need a button on your form that will set the reference to the workbook and close it once the user has completed editing.
If you define the workbooks that you open as a variable - you will be able to close them easily. Keep in mind this does not save the workbook.
Dim DataBook As Workbook
Set DataBook = Workbooks.open ("pathname")
' Do something useful with the file
DataBook.Close
It is not completely clear what you are trying to ask here, but I'll give it my best in providing you a full answer. If you are having no success with the Unload Me statement when it comes to closing a user form, try specifying the full form name in VBA. That is:
Unload UserFormName
If you are trying to close the workbook you have opened (via the user form), you can use the Workbooks.Close method:
Dim wb as Workbook
Set wb = Workbooks.Open(Filename:="C:\example.xls")
wb.Activate
'Close workbook
wb.Close
'Unload form
Unload ExampleForm
More on the use of the Unload statement can be found here:- https://msdn.microsoft.com/en-us/library/aa445829(v=vs.60).aspx
And more on the use of the Workbooks.Close statement can be found here:- https://msdn.microsoft.com/en-us/library/office/ff838613.aspx
I'm not sure what's causing the behavior you describe (inability to click the "Close" X button in the active Excel window). However your current workflow is:
User interacts with form to review/access a file
User clicks a button on the form which unloads the form
User is then expected to manually close out of the file opened in (1)
A better solution would be to remove the third step, and close the workbook from one of the form's event-handlers (UserForm_QueryClose or UserForm_Terminate). Alternatively you could add this to a CommandButton's Click event, but that's not very different than requiring the user to manually close the file.
This could be as simple as:
Private Sub UserForm_Terminate()
' should be called when form Unloads
On Error Resume Next
Workbooks.Close "filename.xlsx"
End Sub
In this manner, the file will be closed any time the user closes or otherwise unloads the userform.
OK I think I found a way around it.
Let's say I have a workbook1 which has a form called ControlPage with command button that opens up workbook2.
Private Sub CommandButton1_Click()
Dim workbook2 As Workbook
Dim workbook1name As String
workbook1name = ThisWorkbook.name
Set workbook2 = Workbooks.Open("workbook2.xlsx")
ControlPage.Hide
Workbooks(workbook1name).Activate
Workbooks("workbook2.xlsx").Activate
End Sub
So basically because 'activate' bit doesn't seem to work properly when I try to activate workbook 2 straight away, I just activate the first, and then the second one ane after another. Twisted but did the trick for me.

Global worksheet variable for userform in excel

I am building a userform that adds data to a worksheet. I have a bunch of sub-routines for my userform, but I'm having issues accessing the variable I set to my worksheet. It's currently a local variable (in a sub) and have tried placing it in a module as discussed here: Can a worksheet object be declared globally in Excel VBA. I've done some further searching but didn't quite get the results I wanted.
I'm quite new to VBA and new to programming in general. I've used Excel quite a bit and want to do more by creating macros and such using VBA. Here's the code I'm currently using:
sub savebutton_click()
Dim trees As Worksheet
Set trees = ThisWorkbook.Sheets("Sheet1")
trees.Cells(1, 1) = Me.TextTreeName
trees.Cells(1, 2) = Me.TextTreeType
End sub
Obviously I cannot access local variables from another subroutine, so I have to make 'trees' global. I created a module and replaced Dim with Public, placed the second line of code in Workbook_Open(), and then tried accessing the 'trees' variable. I get an "Invalid outside procedure" and highlights the code in Workbook_Open() when I hit 'Debug'.
Essentially I just want to be able to access, say, trees.Cells(5,6) from any sub and I'm not sure what else to do with it. Any ideas? Thank you!
It must be a matter of placement ... if you open the VBA IDE and select the ThisWorkbook item in your VBAProject. Double click that item to open it, Select Workbook in the top left dropdown, Select Open in the top right dropdown. This will create your Workbook_Open Sub in the ThisWorkbook object:
Private Sub Workbook_Open()
Set trees = ThisWorkbook.Sheets("Sheet1")
End Sub
Right click your VBAProject and Add Module. In that module you put the global variable:
Public trees As Worksheet
Next you create your form, put the button on that and double click the button. This will generate the button event:
In my case:
Private Sub CommandButton1_Click()
trees.Cells(1, 1) = Me.TextTreeName
trees.Cells(1, 2) = Me.TextTreeType
End Sub
Now if you close the Excel Workbook (save the code and the workbook first) and reopen the Workbook the Workbook_Open() will kick in and set the Worksheet. Now call your Form, and click the button. This will fill the two cells on the given sheet....

Referencing the selection in deactivated Workbook

Private Sub Workbook_Deactivate()
ThisWorkbook.ActiveSheet.Selection.Copy
End Sub
I'd like to copy the selection in the deactivated workbook. But this doesn't work, indeed, I got a run-time error.
Damn! It is possible!
Private Sub Workbook_Deactivate()
ThisWorkbook.Windows(1).Selection.Copy
End Sub
Explanation:
Both ActiveSheet and Selection are children objects of the Application object, not the Workshet or Workbook objects. (See MSDN: Selection and ActiveSheet.) Selection means the currently selected item in the active window. Same for ActiveSheet.
Now it turns out that you can specify a window object for both of them. Normally every Workbook has one window, but you can create multiple windows for each open workbook. Anyhow, every open workbook that you can click and select will have at least one window. This is whateverworkbook.Windows(1).
ThisWorkbook always references the workbook running the macro (that means the workbook actually containing the VBA code). In your case, that is the one you are leaving. (Unless you want the macro to run from any workbook you are deactivating, in which case you'd have to come up with a custom event handler that catches each workbook deactivate event...)
And that's it, really. You can reference a selection in another workbook, you just have to attack it through it's Window.
Thanks for the good question, I have learned something very valuable today. :)

Macro from on open event for worksheet

I have a macro that I want to run as part of open event. I recorded the macro to copy and paste some columns on a worksheet. This macro will only work when I am on that worksheet.
Since I want to run this macro as one of many applications when workbook is open and it doesn't always open on this specific worksheet I would like the code to target the worksheet and run the macro.
Here is my code but for some reason it doesn't work :
Application.Run "'Workbook.xlsb'!Sheet5.Copy_Paste2"
If I'm understanding you, you need to call Copy_Paste2 from ThisWorkbook Open event.
Private Sub Workbook_Open()
Sheet5.Copy_Paste2
End Sub