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