VBA EXCEL - Extract a copy of workbook - vba

Im trying to extract a copy of my workbook to a new file in VBA but I'm getting an "Application or object defined error" and i have no clue whats wrong.
All im using is the command i found on the microsoft site?
Public Function EWbtn()
ActiveWorkbook.SaveCopyAs "C:\CRC Chart Extract.XLS"
End Function
Im very confused :L

As Michal said, the easier way is just create the file first then populate it with your current active workbook. Here is a sample that should be able to get you started
Sub try_me()
Dim workbookPath As String
Dim output_filename As String
'getting your active workbook path
workbookPath = ActiveWorkbook.Path
'pre-defined output filename
output_filename = "my_other_worksheet"
'Copy your current active workbook to the new wb
ActiveWorkbook.Sheets.Copy
'save the workbook
ActiveWorkbook.SaveAs Filename:=x & "\" & y & ".xls"
End Sub
Credit to Smitty here:
https://www.mrexcel.com/forum/excel-questions/139831-create-empty-workbook-visual-basic-applications.html

I got the same error. I solved it by creating the file. Most probably copying can be done to existing file. Add code to create the file before copying to it.

It is doubtful that a function can do this. I tried below code and it's working.
Public Sub EWbtn()
ActiveWorkbook.SaveCopyAs "C:\CRC Chart Extract.XLS"
End Sub

Related

Open the same workbook but different path every week

I would like to open a file that is located in a different folder every week (file name remains the same but new week = new data).
Workbooks.Open "C:\Users\baguette\Documents\W44\L060.xlsx"
The week folder is obviously W44. Is there a way I could use a cell content that would be taken into account in the code?
For example, cell A1 of sheet1 of the file the code is run from would contain the week number that I would manually key in before running the procedure.
I tried this but did not work :
Workbooks.Open "C:\Users\baguette\Documents\& ThisWorkbook.Worksheets(1).Range("A1")\L060.xlsx"
I guess it was a bit rash.
Thank you for your help.
You are very close to your solution. Just try below-
Workbooks.Open "C:\Users\baguette\Documents\" & _
ThisWorkbook.Worksheets(1).Range("A1") & _
"\L060.xlsx"
You can decorate code using string type variable. Check below sub.
Sub OpenSpecificFile()
Dim FolderPath As String
Dim WeekFolder As String
FolderPath = "C:\Users\baguette\Documents\"
WeekFolder = ThisWorkbook.Worksheets(1).Range("A1")
Workbooks.Open (FolderPath & WeekFolder & "\L060.xlsx")
End Sub

Programmatically add workbook event and save it

I have a list of excel files in a spreadsheet. I'd like to loop through them and add a worksheet event to each. Save it, close it and move on to the next. The problem is that when I reopen (manually) the workbook the code is gone.
Inside the for each loop:
Set xl = Workbooks.Open(filepath)
addCode xl 'subroutine to add code
xl.Save
xl.Close SaveChanges:=False
The addCode subroutine is:
Sub addCode(book As Excel.Workbook)
acsh = book.ActiveSheet.CodeName
startline = book.VBProject.VBComponents(acsh).CodeModule.CreateEventProc("SelectionChange", "Worksheet") + 1
book.VBProject.VBComponents(acsh).CodeModule.InsertLines startline, codetoadd
End Sub
If I comment out xl.Close the code is in the workbook and works. I can manually save and close the file and the code remains. I've added a break point between xl.save and xl.close and made a copy of the file. After the code is done neither has the changes. I've tried using xl.saveas and xl.close SaveChanges:=True. All have identical results.
I'm using Excel 2013, I've told excel to trust access to the VBA object model. I've tried using XLS files and XLSM files. Obviously XLSX won't work.
Here is some sample code which is working for me on Excel 2010. The changes I made to your example code are:
use a .xlsm for the target workbook - I know you said you already did that.
reference a specific worksheet in the AddCode sub rather than pick up the sheet name from ActiveSheet.
set the workbook dirty status per Ralph's comment
Don't set the SaveChanges flag when closing the target workbook
Other than that, my version is pretty similar to yours. I think it is the wb.Saved = False line that does the trick i.e. the dirty flag. I tried to use the SaveAs method on the VBProject itself thinking it would be the same as hitting the save button when you are in the VBA Editor itself. However, this just gives unhelpful errors.
Here's the sample code:
Option Explicit
Sub Test()
Dim wbTarget As Workbook
Dim strCode As String
' get target workbook
Set wbTarget = Workbooks.Open("\\server\path\Book3.xlsm")
' test setting code to worksheet change
strCode = "Debug.Print ""Sheet selection changed to: "" & Target.Address"
AddWorksheetChangeCode wbTarget, "Sheet1", strCode
' test saving the target workbook
With wbTarget
' set book to dirty to force the save
.Saved = False
.Save
.Close
End With
End Sub
Sub AddWorksheetChangeCode(ByRef wb As Workbook, strWorksheetName As String, strCode As String)
Dim intInsertLine As Integer
' create stub for event and get line to insert
intInsertLine = wb.VBProject.VBComponents(strWorksheetName).CodeModule.CreateEventProc("SelectionChange", "Worksheet") + 1
' add event logic
wb.VBProject.VBComponents(strWorksheetName).CodeModule.InsertLines intInsertLine, strCode
End Sub

Setting Document Properties while saving individual sheets

I'm not familiar with VBA at all so this has me stumped, hoping someone can help.
I have a template on a sharepoint server that is working correctly. In order to save the xlsm file with the server document properties, I have a command button which runs the following:
Sub UpdateDB()
For Each Prop In ThisWorkbook.ContentTypeProperties
If Prop.Name = "Name" Then
Prop.Value = Range("B8").Value
End If
Next Prop
Filename = Range("B59").Value
ActiveWorkbook.SaveAs Filename:=Filename, FileFormat:=52
End Sub
This is working well.
I now have another template which I want to do a similar thing but there are some complications:
I have several worksheets which I would like saved as individual files containing only the said worksheet.
The document properties for each file should different, based on a cell in each worksheet.
Now I have managed to setup point 1 and it's working OK using the following code:
Sub NewSub()
Worksheets("EMP1").Activate
Filename = Range("B1").Value
Dim wb as Workbook
Application.ActiveSheet.Copy
Set wb = ActiveWorkbook
With wb
.SaveAs Filename:=Filename, FileFormat:=52
End With
End Sub
This is working well but if I try adding in code to set the Document Properties, it doesn't work, it won't carry them through to the new file. I have tried adding the code which sets the document properties after line 2 and I have tried adding it also after line 7; it doesn't throw an error but it doesn't set any document properties either. Any help on this would be much appreciated. Thanks.

Open an excel workbook after code executes

I know this has been asked before, but for the life of me I cannot get this simple code to work. I keep getting the compile error "User-defined type not defined" on Dim wbopen As Workbook
line. I know the workbook has to be open to define it, and the file path should be Z:\Manufacturing\02- Schedules\01- Buffer Prep
while the file name is the only .xls in the folder. Why is this happening? Also, this is executing in a Word file. Not sure if that matters. Thanks everyone!
Sub fileopen()
Dim wbopen As Workbook
Dim strFileName As String
Dim strFilePath As String
strFilePath = "Z:\Manufacturing\02- Schedules\01- Buffer Prep\"
strFileName = Dir(strFilePath & "*.xls")
Set wbopen = Workbook.Open(strFileName)
End Sub
It does matter that it is a Word Document. You have to add a reference to Microsoft Excel Object Library. From the top bar:
Tools -> References -> find Microsoft Excel [version number] Object Library and check it.

How will this variable respond

I'm using Excel VBA but I think this is quite a generic question.
I have the following declaration
Public newReport As Excel.Workbook
Later in the code, after I've opened and named an xlsx file MyBook.xlsx I point this variable at the file:
Set newReport = Excel.Workbooks("MyBook.xlsx")
I'm getting slightly confused again re. variable behaviour.
If I later have MyBook.xlsx open and I execute ActiveWorkbook.SaveCopyAs and give it a new name say MyBookNew.xlsx will the variable newReport be pointed at the new workbook?
Example of related code is the following:
Public newReport As Excel.Workbook
Sub FileExperiment()
Set newReport = Excel.Workbooks.Add
newReport.SaveAs ThisWorkbook.Path & "\MyBook.xlsx"
Set newReport = Excel.Workbooks("MyBook.xlsx")
ActiveWorkbook.SaveCopyAs ThisWorkbook.Path & "\MyNewBook.xlsx"
newReport.Close False
End Sub
newReport will be unchanged.
Cut from the help file, regarding the command SaveCopyAs:
Saves a copy of the workbook to a file but doesn't modify the open workbook in memory.