I am writing a reporting system where the user fills out a form and a form button runs a macro to save the file with a name based on several fields including a timestamp.
All the data is is also on a second sheet but in one row for ease of copying to a master sheet.
I am trying to to extend the save macro to copy this row to the last line of a second workbook.
This was successful when the macro was run from a separate workbook but I can't for the life of me work out how to do it from within the file itself.
I've triple checked the paths themselves, I know they're right as the new files are being created, I've run msgbox in the code to check the filename and the variable are the same too.
timestampedfile = Worksheets("single_line").Range("b3")
totalpath = Path & timestampedfile & ".xlsm"
ActiveWorkbook.SaveCopyAs filename:=totalpath
master_wb = "s:\blah\blah\blah.xlsx"
master_sht = "Master_Database"
contact_wb = totalpath
contact_sht = "single_line"
Workbooks.Open (master_wb)
Workbooks.Open (contact_wb)
MsgBox (totalpath)
Workbooks(contact_wb).Worksheets(contact_sht).Range("A3:AQ3").Copy Worksheets(master_wb).Sheets(master_sht).Range("A" & Rows.Count).End(xlUp)(2)
'
Both the Workbooks open so I know the paths are right, can anyone help?
Solution by OP
Solved thanks to comment about workbook variables by BigBen:
Use workbook variables, instead of referencing the workbook by name: Dim masterWb as Workbook, then Set masterWb = Workbooks.Open("s:\blah\blah\blah.xlsx" ). Similarly for the contact workbook. You might consider using worksheet variables too, instead of using sheet names.
Code changed to:
Dim master_wb As Workbook
Dim contact_wb As Workbook
Dim master_sht As Worksheet
Dim contact_sht As Worksheet
Path = "S:\blah\" & Worksheets("report").Range("c8") & "\"
filename = Worksheets("back_end_formulas").Range("e10")
timestampedfile = Worksheets("single_line").Range("b3")
totalpath = Path & timestampedfile & ".xlsm"
ActiveWorkbook.SaveCopyAs filename:=totalpath
SetAttr totalpath, vbReadOnly
Set master_wb = Workbooks.Open("S:\blah\Master_Database2.xlsx")
Set master_sht = master_wb.Sheets("Master_Database")
Set contact_wb = Workbooks.Open(totalpath)
Set contact_sht = contact_wb.Sheets("single_line")
ThisWorkbook.Activate
contact_sht.Range("A3:AQ3").Copy master_sht.Range("A" & Rows.Count).End(xlUp)(2)
master_wb.Close SaveChanges:=True
contact_wb.Close SaveChanges:=False
ActiveWorkbook.Close SaveChanges:=False
I'm new to VBA coding. I'm trying to open workbooks, read and write to them.
I have to open the first workbook to start the code.
This code opens opens other workbooks and writes into them.
This worked fine for testing purposes. However, when I have two workbooks open and start the code, incorrect value is stored.
Here is the code:
Sub Workbook_test ()
WB_path = "C:\Users\az54\Macro_files\"
Source_File = WB_path & "Test_Source.xlsm" ' Source file name
File_Test = Dir(Source_File)
If (File_Test = "") Then
MsgBox "Source file not found at " & Source_File & vbCr & vbCr & "Check for Source file and RESTART"
GoTo FINISH
Else
Set Source_WB = Workbooks.Open(Source_File)
MsgBox "Source Workbook name = " & Source_WB.Name & vbCr & "Source Sheet name = " & setup_tab
Set Src_Sheet = Source_WB.Worksheets(setup_tab)
End If
FINISH:
End Sub
The variable Source_WB is not getting the workbook name from variable Source_File, instead it is getting loaded with another open workbook.
Any ideas?
Thanks
Change
Src_Sheet = Source_WB.Worksheets(setup_tab)
to
Src_Sheet = Source_WB.Sheets("setup_tab")
I am trying to delete the contents of few cell in the saved copies of my workbook that is under different file names. As code below, this is deleting the content from original workbook and retaining the content in the saved wb. It is doing the right opposite task that I wanted for!
Also, any suggestion on how to disable few modules and delete few pictures in the saved wb ?
Thanks in Advance for help !
Sub SaveAsNewCopy()
Dim Path As String
Dim FileName1 As String
Application.DisplayAlerts = False
FileName1 = Range("D3")
ThisWorkbook.SaveCopyAs FileName:="C:\Users\..\..\..\" & FileName1 & "-" & "List" & ".xlsm"
MsgBox "File Saved successfully!", , "Save"
ThisWorkbook.Sheets("Sheet1").Range("E5:F5").ClearContents
ThisWorkbook.Sheets("Sheet1").Range("E9:F9").ClearContents
Application.DisplayAlerts = True
End Sub
You need to get a handle on the workbook you just saved, make the changes you want and then save it again. The easiest way to do this is to assign a variable to it. In your declarations do something like this:
Dim wb as Workbook
then before your save-as line assign the saved workbook to that variable like this:
Set wb = ThisWorkbook.SaveCopyAs FileName:="C:\Users......\" & FileName1 & "-" & "List" & ".xlsm"
Then you can work with wb as required as save it with wb.Save True etc etc
I have an Excel Workbook that on form button click I want to save a copy of the workbook with the filename being the current date.
I keep trying the the following
ActiveWorkbook.SaveAs ("\\filePath\FormFlow To MSExcel\" & Left(Now(), 10)) but am receiving Run-time error '1004': Method 'SaveAs' of object'_Workbook' failed.
Can anyone assist me with this? I'm still very new to developing for Excel.
Most likely the path you are trying to access does not exist. It seems you are trying to save to a relative location and you do not have an file extension in that string. If you need to use relative paths you can parse the path from ActiveWorkbook.FullName
EDIT:
Better syntax would also be
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=xlWorkbookNormal
Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'
Stop recording and you can start inspecting your code.
I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"
Option Explicit
Sub SaveFile()
Dim fdate As Date
Dim fname As String
Dim path As String
fdate = Range("A1").Value
path = Application.ActiveWorkbook.path
If fdate > 0 Then
fname = "Event " & fdate
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
MsgBox "Chose a date for the event", vbOKOnly
End If
End Sub
Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!
It could be that your default format doesn't match the file extension. You should specify the file format along with the filename, making sure the format matches the extension:
With someWorkbook
.SaveAs "C:\someDirector\Awesome.xlsm", fileformat:=xlOpenXMLWorkbookMacroEnabled
End With
OTOH, I don't see an extension on your .SaveAs filename. Maybe you need to supply one when doing this programmatically. That makes sense--not having to supply an extension from the GUI interface is convenient, but we programmers are expected to write unambiguous code. I suggest adding the extension and the matching format. See this msdn page for a list of file formats. To be honest, I don't recognize a lot o the descripions.
xlExcel8 = 56 is the .xls format
xlExcel12 = 50 is the .xlsb format
xlOpenXMLWorkbook = 51 is the .xlsx format
xlOpenXMLWorkbookMacroEnabled = 52 is the .xlsm format
xlWorkbookDefault is also listed with a value of 51, which puzzles me since I thought the default format could be changed.
I successfully use the following method in one file,
But come up with exactly the same error again...
Only the last line come up with error
Newpath = Mid(ThisWorkbook.FullName, 1, _
Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & "ABC - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
ThisWorkbook.SaveAs (Newpath)
I was struggling, but the below worked for me finally!
Dim WB As Workbook
Set WB = Workbooks.Open("\\users\path\Desktop\test.xlsx")
WB.SaveAs fileName:="\\users\path\Desktop\test.xls", _
FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
Dim NuevoLibro As Workbook
Dim NombreLibro As String
NombreLibro = "LibroPrueba"
'---Creamos nuevo libro y lo guardamos
Set NuevoLibro = Workbooks.Add
With NuevoLibro
.SaveAs Filename:=NuevaRuta & NombreLibro, FileFormat:=52
End With
'*****************************
'valores para FileFormat
'.xlsx = 51 '(52 for Mac)
'.xlsm = 52 '(53 for Mac)
'.xlsb = 50 '(51 for Mac)
'.xls = 56 '(57 for Mac)
'*****************************
When working with large amount of data where .xlsx workbook is needed, use the following syntax
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=51
(For more FileFormats see documentation.)
I think your issue was that when you use Now(), the output will be "6/20/2014"... This an issue for a file name as it has "/" in it. As you may know, you cannot use certain symbols in a file name.
I need to export data in a sheet to a text file without changing the file name (i.e. not doing "save as". Also it would be great if the file name could look at the previous like file name in the folder and increase by 1 digit (i.e. :file_1.txt, file_2.txt, etc.)...
Thanks!!
If you want to avoid the current name of your excel file being changed, just save the current worksheet, not the whole workbook (the VBA equivalent of the SaveAs function is ActiveWorkbook.SaveAS, to save just the current sheet use ActiveSheet.SaveAS).
You can use the following macro:
Sub Macro1()
Application.DisplayAlerts = False
ActiveSheet.SaveAs Filename:="NewFile.txt", FileFormat:=xlTextWindows
Application.DisplayAlerts = True
End Sub
Toggling the DisplayAlerts property avoids a message box that is displayed if the given file already exists.
If want to save more than one sheet, you need to iterate through the Sheets collection of the ActiveWorkbook object and save each sheet to a separate file.
You can get a new file name as illustrated below, it includes a date. If you would like to add some details on what you want to export, you may get a fuller answer.
Function NewFileName(ExportPath)
Dim fs As Object '' or As FileSytemObject if a reference to
'' Windows Script Host is added, in which case
'' the late binding can be removed.
Dim a As Boolean
Dim i As Integer
Dim NewFileTemp As string
Set fs = CreateObject("Scripting.FileSystemObject")
NewFileTemp = "CSV" & Format(Date(),"yyyymmdd") & ".csv"
a = fs.FileExists(ExportPath & NewFileTemp)
i = 1
Do While a
NewFileTemp = "CSV" & Format(Date(),"yyyymmdd") & "_" & i & ".csv"
a = fs.FileExists(ExportPath & NewFileTemp)
i = i + 1
If i > 9 Then
'' Nine seems enough times per day to be
'' exporting a table
NewFileTemp = ""
MsgBox "Too many attempts"
Exit Do
End If
Loop
NewFileName = NewFileTemp
End Function