I am writing a piece of code in Excel VBA in which I needed to create a macro which allows the user to click the ActiveX button as a result of which the file is then saved to a specified location. Once this new file is created, I wanted to code so the new file (which successfully saves in the alternate specified location) does not have the ActiveX Command Button is not present. Also, once the button is clicked from the original file, I wanted to somehow make the master file close and the newly saved file to automatically open. Please can someone help?
Code so far:
Sub CommandButton1_Click()
ActiveSheet.Copy
Dim SaveName As String
SaveName = ActiveSheet.Range("C1").Text
With ActiveWorkbook
.SaveAs "File path Specified" & _
SaveName & ".xls"
.Close 0
End With
End Sub
My first solution (depending on what you really need to do) is the following:
Firstly you will need this:
Me.SaveCopyAs "<full_Path>"
See more on this here: https://msdn.microsoft.com/en-us/library/office/ff835014.aspx
This will create a copy of the file to the specified path with whatever name you want. Before you do that, you could hide your button and then use save as copy to save it with the button hidden.
Finally if you want to close the original and open the copy then you have to give to the copy a different name. Then open the new file and close the original.
Your code should look similar to this:
Sub CommandButton1_Click()
ActiveSheet.Copy
Dim SaveName As String
SaveName = ActiveSheet.Range("C1").Text
With ActiveWorkbook
.Worksheets("<your_worksheet>").CommandButton1.visible = False
.SaveCopyAs "File path Specified" & SaveName & ".xls"
End With
Workbooks.Open ("File path Specified" & SaveName & ".xls")
Workbooks("<Original_name.xlsm>").close False
End Sub
Another Solution could be saving the workbook with SaveAs. Before that save the orginal. Hide the button. And saveas will close the original and open the new one automatically.
Your code should look something like that:
Sub CommandButton1_Click()
ActiveSheet.Copy
Dim SaveName As String
SaveName = ActiveSheet.Range("C1").Text
With ActiveWorkbook
.Save
.Worksheets("<your_worksheet>").CommandButton1.visible = False
.SaveAs "File path Specified" & SaveName & ".xls"
End With
End Sub
Related
I am trying to write a macro in VBA that saves the original workbook as a macro free workbook and then re-open the original macro enabled file, but ehat I have written is bugging out when it tries to open code (which is the last line of code). The error I get is a dialogue box that states that the file is unable to be found, however the file path provided is correct. Is the issue that I am trying to finish running the macro, while the workbook that is open is a generic Excel workbook (not macro enabled)? Code is below:
Sub SaveReport()
' SaveReport Macro
Dim strFileName As String, strOpen As String
strFileName = Application.Range("Attach").Value
strOpen = Application.Range("Open").Value
ActiveWorkbook.Save
Sheets("Email").Visible = False
ActiveWorkbook.SaveAs (ThisWorkbook.Path & "\" & strFileName & ".xlsx"), FileFormat:=xlOpenXMLWorkbook
Workbooks.Open strOpen
End Sub
I have the following VBA:
Sub Create_Sent_File()
ActiveWorkbook.SaveCopyAs "C:\Users\" & Environ("Username") & "\Desktop\" & "Sent_File" & ".xlsm"
ActiveWorkbook.Close SaveChanges:=False
End Sub
The code creates a new file called "Sent_File" on the desktop of the user.
All this works fine so far.
However, after the file is created I want to close the original Excel file.
The exact same way I would do it if I have three Excel files open and then I close one of them.
Therefore, I tried to go with this formula:
ActiveWorkbook.Close SaveChanges:=False
Now, the issue is that the workbook is closed but Excel somehow remains open:
What do I need to change in my code so:
a) The current workbook in which I run the VBA is closed.
b) Other workbooks in Excel remain open.
c) Excel does not stay open as seen in the screenshot.
You're almost there, but you need a reference to the parent application before you then trigger its closure.
Sub Create_Sent_File()
Dim xlParent As Excel.Application
ActiveWorkbook.SaveCopyAs "C:\Users\" & Environ("Username") & "\Desktop\" & "Sent_File" & ".xlsm"
ActiveWorkbook.Saved = False
Set xlParent = ActiveWorkbook.Parent
xlParent.Quit
End Sub
Having set the Saved flag for the current workbook to False you can close the host Excel app without triggering any confirmation boxes.
If you have other workbooks open that you also want to close without confirmation, you'll need to work through the Workbooks collection, setting the Saved property of each to False before then proceeding with quitting the host Excel app.
I have created a VBA code which creates a folder, named after a referenced cell, then within that folder I have created multiple sub folders. What I now want is a new code to save the excel sheet within one of the sub folders with a specific name, this is what I have so far. I think I am writing the path wrong or maybe using the wrong syntax. Please help ;)
I have included a copy of the code and an image hopefully it uploads correctly.
Private Sub CommandButton1_Click()
' automates the saving
Dim path As String
Dim filename1 As String
path = "T:\Estimating\Williaam Cox Project Enquiries 2018\" & Range("SaveRef") & "\Costings"
filename1 = Range("SaveRef").Text
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=path & "Costing Sheets" & ".xlsm", FileFormat:=52
Application.DisplayAlerts = True
End Sub
enter image description here
you're missing a "\" at the end of your path.
I can't get my macro running in AfterSave or BeforeClose event.
I export one sheet to a .csv file, that's already working well with the next code when I link this macro to a button:
Sub CopyToCSV()
Worksheets("LastLots").UsedRange.Rows("1:5").Calculate
ThisWorkbook.Save
Dim MyPath As String
Dim MyFileName As String
'The path and file names:
MyPath = "D:\Data\PW\2018\"
MyFileName = "LastLots-exported"
'Makes sure the path name ends with "\":
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
'Makes sure the filename ends with ".csv"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
'Copies the sheet to a new workbook:
Sheets("LastLots").Copy
'The new workbook becomes Activeworkbook:
With ActiveWorkbook
Application.DisplayAlerts = False
'Saves the new workbook to given folder / filename:
.SaveAs Filename:= _
MyPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False
'Closes the file
.Close False
Application.DisplayAlerts = True
End With
End Sub
The code above is in a module. As I said, when linked to a button and press that button, it works very well.
But I want it running when the user saved the file.
Fot this, I put the next code in ThisWorkbook:
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
If Success = True Then
Call CopyToCSV
End If
End Sub
I tried various things, like putting the code of the macro inside the AfterSave-event, and disable/enable Application.EnableEvents before and after calling CopyToCSV but nothing works for me...
Does anyone have a suggestion? I'm out of mind, and every topic I find on Google say to put the code in ThisWorkbook, but already done that.
Just typing the code somewhere does not make it an event handler.
You must enter "ThisWorkbook", look at the top bar, select "ThisWorkbook" and the desired event.
Excel will then automatically create the empty Sub for you, associated with the event. You insert your code inside that Sub.
More details: https://www.excelcampus.com/vba/code-modules-event-procedures/
Hints: before any if, test if the script is being run, add a message such as MsgBox "After save!!!"
This will help you identify if the problem is the event not being called or your code not being run properly.
I am having this weird problem when saving my sheet into onedrive sync folder. Basically what i am doing with the below code is that I copy a sheet from my workbook then save it into a sync folder. When it does this, a saved copy with the filename that is stored in a specific cell together with another copy with the same saved name with a 1 at the back of the file name will appear in the sync folder. When i step over to test the code, no such error occur. The error only occur if I run the macro. May i know why? Below is my code;
Sub SheetSplit1()
'
'Creates an individual workbook for each worksheet in the active workbook.
'
Dim wbDest As Workbook
Dim wbSource As Workbook
Dim sht As Object
Dim strSavePath As String
Dim sname As String
Dim relativepath As String
Set wbSource = ActiveWorkbook
'For Each sht In wbSource.Sheets
Sheet10.Copy
Set wbDest = ActiveWorkbook
sname = Sheet9.Range("I5") & "_" & _
Format(Sheet9.Range("I8"), "ddmmmyyyy") & ".xlsx"
relativepath = "C:\Users\" & Environ$("Username") & _
"\SharePoint\Open Project Transition Check - Doc\Transition Dashboard Report\" & sname 'use path of wbSource
'wbDest.Sheets(1).Range("A1").Clear 'clear filename from new workbook cell A1
Application.DisplayAlerts = False
ActiveWorkbook.CheckCompatibility = False
ActiveWorkbook.SaveAs Filename:=relativepath, FileFormat:=xlOpenXMLWorkbook, _
CreateBackup:=False
Application.DisplayAlerts = True
wbDest.Close False 'close the newly saved workbook without saving (we already saved)
'Next
MsgBox "DashBoard Report Saved!"
End Sub
Greatly appreciate anyone who could assist me. Thanks.
I wish I could give a definitive answer, or Microsoft would contribute.
I have similar connected problems. It seems that another version of the file may be or "appear to be" open elsewhere, thus preventing excel/Onedrive from completing the save action.
Rather than overwrite it(lets face t, that was the command) it creates a "version" filename(1).
I am guessing this is the same as when you do it manually and you are asked to resolve a conflict.
So far I have failed to find out how you can discover and solve the problem in code.
I solved it in one instance by mapping a drive on the offending desktop and first closing any open versions before save, but that is not a robust long term solution.
Test this by setting Application.DisplayAlerts = True and capturing errors.
"On error got catch" after the last dimension line then
"exit function
catch:
msgbox err.description"
before "end sub"