What am I missing in my code that doesn't "Close" the workbook (.xlsm) after saving it? - vba

What is the proper code to input in the module/button that will specifically prompt the user to "SaveAs", "Close" the (.xlsm) file, and open the same "New" sheet again?
I want to create an excel micro-enabled file .xlsm that will have a button called, "Save&New". The module/button will SaveAs, close the current file and open the same file again. For instance, when I'm filling out an audit and using the .xlsm sheet, I want to click the "Save&New" button for it to SaveAs, close it, and open the same file again but not the one I saved. Look at it has a template; only that I want the button to SaveAs, close the file, and open a "new" fresh file automatically.
Here is what I have so far:
In this image you see that I created the button called, "Save&New".
[enter image description here][1]
When I click on the "Save&New", it will "SaveAs" the .xlsm sheet.
[enter image description here][2]
This is where I need help. After saving the sheet, I want the workbook to "Close" the file.
And open the same sheet before to work on a "New" audit workbook form (.xlsm). (Not the sheet that was saved, but the sheet open before modifying it)
This is the code that I have inside the module/button called, "Save&New":
Sub Button7_Click()
Application.Dialogs(xlDialogSaveAs).Show
Dim oWB As Excel.Workbook
For Each oWB In Application.Workbooks
If oWB.Name = "_temp.xls" Then
oWB.Close
Exit For
End If
Next
Set oWB = Nothing
Workbooks.Open ("Communications Subdivisions System Audit.xlsm")
ActiveWorkbooks.Close
End Sub
The code currently "SaveAs" and it opens a "New" sheet of the same one that was used before saving it. The problem is that it doesn't close the workbook that was saved before, although it does open the "New" sheet.
Specifically, my question is:
What am I missing in my code that doesn't "Close" the workbook (.xlsm) after saving it and still opens a "New" sheet again?

Unless there is more involved with the macro, you might be able to accomplish this entirely via a "Template" feature already built into Excel and save yourself a ton of work and trouble.
Get your "new" file the way you want it, choose "Save As", and then in the File Types section choose "Excel Template (*.xltx)". Note this will change the selected save folder, so put the save dialog back where you really want the file and save it.
Now, every time you open this file you get a new copy, and when you do a regular save it won't make changes to the original.

Seems that the _ is comparing as a wildcard not as a literal string.
I played around and for some reason using the wildcard escape key doesn't work unless you compare with Like instead of =
This should work:
Dim oWB As Excel.Workbook
For Each oWB In Application.Workbooks
If oWB.Name Like "[_]temp.xlsm" Then
oWB.Close
Exit For
End If
Next

Related

VBA Ribbon Bar Integration

I have an Excel macro that performs a few functions on a document (Creates as form, and a few emails) all from MS-Word documents. If the macro is executed from the main spreadsheet (where the macro is), everything works normally. I want to place this macro on the ribbon allowing a user to launch it without having (or knowing where the main excel document is located or having it open). I created a sub to check to see if the spreadsheet was open and modified the ribbon to include an icon for the macro.
Which works. However, when launched from the ribbon while the main Excel spreadsheet is not open, it opens the workbook and runs the macro in entirety (Without executing the open workbook line of the macro). I assume the spreadsheet is being open because the macro that is being called resides with it (makes sense). Since the macro is dependent on the data contains in the spreadsheet, I need to allow the users to modify it and then re-running the macros from the ribbon again.
Does anyone have a recommended approach or best practices? Thank you in advance.
Sub MainForm()
Dim WorkingFolder As String
Dim File01 As String 'Main Excel Data File, where all data is
Dim File02 As String 'Preliminary Email to send to user
Dim File03 As String 'Final Email to Send to user when production is complete
Dim wb As Workbook
WorkingFolder = "C:\Temp\"
File01 = "01-MainData.xlsm"
File02 = "02-PreProductionEmail.docx"
File03 = "03-FinalProductionEmail.docx"
If wbIsOpen(File01) = True Then
MsgBox "Workbook Is Open"
Run ("'C:\Users\Guest\Nextcloud\Documents\Excel Forms\02-TEST-Production Request-Data.xlsm'!CreateProductionForm")
Else
MsgBox "The Main Datafile is not open, verify the last row before re-runing", vbOKOnly, "Not Open"
Set wk = Workbooks.Open(WorkingFolder & DataFile)
End If
End Sub
The Guide mentioned by Ricardo was not quite what I needed but it was helpful and did put me on the right track. Thank you again Ricardo. To get this working, I needed to do the following.
1 - Make the procedure above its own separate *.xlam file (saved as an add-in).
2 - Add the add-in to start automatically via the developers tab
3 - Add the Macro to the Ribbon.
I have modified the sample above to included the open statement along with the statement that executes a macros from another workbook.
Appreciate the guidance.

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.

Excel VBA - close an active table/document by name only - NOT filepath

i have a workbook where i regularly update stock prices from a yahoo link. it opens up a read only file named 'table'. below is an example link
http://real-chart.finance.yahoo.com/table.csv?s=INTC&a=05&b=9&c=2000&d=06&e=7&f=2016&g=d&ignore=.csv
things get messy when i have multiple 'table' file open that results in several additional clicks to import the data.
is there a way i can have a macro where any csv/xls files open named 'table' can be closed?
the function used to get this data is
=HYPERLINK("http://real-chart.finance.yahoo.com/table.csv?s=INTC&a=05&b=9&c=2000&d=06&e=7&f=2016&g=d&ignore=.csv","link")
and i've used similar close workbook scripts before, but i cannot for the life of me figure out how to reference this open file for it to be closed
This assumes that the files open in the same Excel instance as the one running the code, and also that you don't want to save any changes to the open files.
Sub CloseTableWorkbooks()
Dim wb as Workbook
For each wb in Application.Workbooks
If Instr(1, wb.Name, "table") Then wb.Close False
Next
End Sub
Dim book As Workbook
For Each book In Application.Workbooks
if book.name = "table.xls" or book.name = "table.csv" then
book.close
end if
Next
You'll get some messages like "Do you want to save before you close?" or the like, which Excel normally does. You can prevent them too but I'm not sure if you want that or not.

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.

Saving file with macro

I entered the following code into Visual Basic.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub
If Intersect(Target, Range("$D$10:$S$29")) Is Nothing Then
ActiveWindow.Zoom = 80
Else
ActiveWindow.Zoom = 100
End If
End Sub
It works well to zoom in when a certain range is selected, and to zoom out when anywhere else on the page is selected.
When I go to save the workbook, the following message comes up:
"The following features cannot be saved in macro-free works:
- VB project
To save a file with these features, click No, and then choose a macr-enabled file type in the File Type list.
To continue saving as a macro-free workbook, click Yes."
When saving I have changed the "save as type" to "Excel Macro-Enabled Workbook". This saves the text in the editor, but when I re-open the file, the macro doesn't work.
I have also saved the file without the macro entered as an "Excel Macro-Enabled Workbook" and then copied the macro into the workbook, checked to see if the macro works (it does), then save the file, close and re-open.
The say outcome of the macro being saved but not working.
How can I save this workbook so that the macro is saved with it and works each time I open the file?
Thank you very much in advance for your help.
#user2879835, After you saved the workbook as "Excel Macro-Enabled Workbook" and while opening the same does it asking any security warnings like "Macros have been disabled"?...and also Worksheet_Change occur when cells on the worksheet either changed by the user or by any link.