VBA:adding files with new version _vX, with separate dates - vba

I am having trouble with creating new version, with the dates selected by the users.
So here I have 2 separate workbooks:
1) Macro - where the users will click the button and generate the macro
2) Report template - when the users click the macro, the figures will be generated into the templates, with the dates in the naming convention, and the version.
The report template naming convention looks like this : BSLCT_DDMMYYYYG where DDMMYYYY is the date, that the users will select in the report template.
So when the report is generated, it will SaveAs another file i.e BSLCT_10072020G.
The code I used to generate is as follow:
Sub Naming reports()
Windows("BSTCT_DDMMYYYYG.xls").Activate
Sheets("G.0(GenInfo)").Select
ActiveWorkbook.SaveAs Path & "\BSLCT_" & REPORT_DATE & "G.xls"
ActiveWorkbook.Close
End Sub
where i define the REPORT_DATE before that.
Now, the users need to have a versioning in their file naming as well, which is something like BSTCT_DDMMYYYYG_vX.xls. So as long as the users run the macro, the macro will generate a new version, regardless of whether the date has already existed.
I managed to create a _v1 using the following codes:
Sub version
Windows("BSTCT_DDMMYYYYG.xls").Activate
Sheets("G.0(GenInfo)").Select
If InStr(ActiveWorkbook.Name, "_v") = 0 Then
fileName = ActiveWorkbook.Path & "\" & Left(ActiveWorkbook.Name,
InStr(ActiveWorkbook.Name, ".") - 1) & "_v1." & ext
ActiveWorkbook.SaveAs (fileName)
Else
index = CInt(Split(Right(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - InStr(ActiveWorkbook.Name, "_v") - 1), ".")(0))
index = index + 1
fileName = ActiveWorkbook.Path & "\" & Left(ActiveWorkbook.Name,InStr(ActiveWorkbook.Name, "_v") - 1) & "_v" & index & "." & ext
End If
ActiveWorkbook.SaveAs (fileName)
End Sub
However, after generating the v1, I couldn't generate v1 onwards, because i need to activate the "BSTCT_DDMMYYYYG.xls" window to pick up the report date, this will then break my codes.
Also, while I am adding the version, at the same time i would like to get the DDMMYYYY into the naming too.
How can I do that?
I really appreciate your helps.
now i am trying to keep adding the newer version with the following code:
Sub SaveNewVersion()
Dim fileName As String, index As Long, ext As String, sVersion As String
arr = Split(ActiveWorkbook.Name, ".")
ext = arr(UBound(arr))
sVersion = "_v"
Windows("BSLCT_DDMMYYYYG.xls").Activate
Sheets("G.0(GenInfo)").Select
If InStr(ActiveWorkbook.Name, "_v") = 0 Then
fileName = ActiveWorkbook.Path & "" & Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, ".") - 1) & "_v1." & ext
ActiveWorkbook.SaveAs "\BSLCT_" & REPORT_DATE & "G" & sVersion & index & ".xls"
Else
index = CInt(Split(Right(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - InStr(ActiveWorkbook.Name, "_v") - 1), ".")(0))
index = index + 1
fileName = ActiveWorkbook.Path & "" & Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, "_v") - 1) & "_v" & index & "." & ext
ActiveWorkbook.SaveAs "\BSLCT_" & REPORT_DATE & "G " & sVersion & index & ".xls"
End If
ActiveWorkbook.Close
End Sub
but at first it keeps replacing my first version, and then saying that this line of code:
index = CInt(Split(Right(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - InStr(ActiveWorkbook.Name, "_v") - 1), ".")(0)) has syntax error.
Does anyone can help on this? I am really clueless where can I modify this.

Try this:
Sub SetNewName()
Dim wbk As Workbook
Dim sDate As String
Dim sVersion As String
sDate = Format(Date, "ddMMyyyy")
sVersion = "_v1"
Set wbk = Application.Workbooks("BSTCT_DDMMYYYYG.xls")
wbk.SaveAs ActiveWorkbook.Path & "\" & sDate & sVersion & ".xls"
End Sub

Related

Is there a way to Get Last Directory so I can Save As into?

I am able to create a new directory on my desktop, my issues is that I don't know how to save multiple files into that folder, within the same Sub, since it has a dynamic name.
Option Explicit
Sub Make_Folder_On_Desktop()
Dim selectionsheet As Worksheet
Dim Group As Variant
Dim amount As Long
Dim BU As Long
Dim BUname As Variant
Dim sFilename As Variant
Set selectionsheet = Sheets("Project Selection")
Group = selectionsheet.Range("A19").Value
amount = selectionsheet.Range("B19").Value
BU = selectionsheet.Range("B6").Value
BUname = selectionsheet.Range("C6").Value
sFilename = BU & " - " & BUname
MkDir Group & " - " & amount & " - " & Format(Date, "mm-dd-yyyy") & " - "
& Format(Time, "hhmmss")
ActiveWorkbook.SaveAs ThisWorkbook.Path & "\" & sFilename
End Sub
Last line is where I'm having the issue. I have "ThisWorkbook.Path" but can't figure out how to get it into the new folder I just created.
MkDir Group & " - " & amount & " - " & Format(Date, "mm-dd-yyyy") & " - " & Format(Time, "hhmmss")
It's hard to know what the folder name is that you just created, because that instruction is responsible for too many things. Split it up.
Build/concatenate a folder name
Make a directory by that name
If we split up the work, things get much simpler:
Dim path As String
path = Group & " - " & amount & " - " & Format(Date, "mm-dd-yyyy") & " - " & Format(Time, "hhmmss")
MkDir path
And now we have the path in the ...path variable, readily usable for anything you might want to do with it:
ActiveWorkbook.SaveAs path & "\" & sFilename
As a side note, if you make the date format yyyy-mm-dd instead, you're ISO-compliant (i.e. the date is unambiguous everywhere in the world), and the folders become sortable by name.
Note that the procedure's name is misleading: it doesn't care where the folder is, and there's nothing that says it's under %USERPROFILE%\Desktop. Use Environ$("USERPROFILE") to retrieve the base path for the current user's profile directory.

VBA: Saving without overwriting existing files

how can I make sure that my VBA code is not overwriting existing files while saving?
Example: I'm saving every sheet as a new workbook, and want to have v1, v2, v3 etc. With the code below I'm always overwriting the existing file, as every file I save has the same file name with "_V1" ending...
NewWbName = Left(wbSource.Name, InStr(wbSource.Name, ".") - 1)
For i = 1 To 9
'check for existence of proposed filename
If Len(Dir(wbSource.Path & Application.PathSeparator & NewWbName & "_V" & i & ".xlsx")) = 0 Then
wbTemplate.SaveAs wbSource.Path & Application.PathSeparator & NewWbName & "_V" & i & ".xlsx"
Exit For
End If
Next i
If i > 9 Then
'_V1.xlsx through _V9.xlsx already used; deal with this situation
MsgBox "out of options"
wbTemplate.Close False 'close template
Next wsSource
wbSource.Close False 'close source
End If
End Sub
Loop through various _Vn.xlsx variations until you find one that isn't there.
dim i as long, NewWbName as string
NewWbName = Left(wbSource.Name, InStr(wbSource.Name, ".") - 1)
for i=1 to 9
'check for existence of proposed filename
if len(dir(wbSource.Path & Application.PathSeparator & NewWbName & "_V" & i & ".xlsx")) = 0 then
wbTemplate.SaveAs wbSource.Path & Application.PathSeparator & NewWbName & "_V" & i & ".xlsx"
exit for
end if
next i
if i>9 then
'_V1.xlsx through _V9.xlsx already used; deal with this situation
msgbox "out of options"
end if
If you are going to raise the loop into double digits, perhaps ... & "_V" & Format(i, "00") & ".xlsx would be better so that a folder sorted by name puts them in the correct order.
Recommend using a date and time stamp for so many versions.
“V” & Format(date, “yyyymmdd”) & format(time, “hhmmss”) & “.xlsx”
Yes, you may still want to check for an existing file, but it’s seldom the user will submit input in less than a second

VBA - Save macro naming workbook

I have code below to save the current workbook and attach today's date to the end of the file name. How would I modify the code so if two copies of the workbook were to be saved on the same day, the first one would save normally as "Workbook Name, Today's Date.xlsm" and the second one would save as "Workbook Name, Today's Date Copy 2.xlsm" instead of "Workbook Name, Today's Date, Today's Date.xlsm" (Attaching the Date twice to the end of the file name, which is what it does now). Same thing if the workbook were to be saved 3,4,5 times a day they should save as Copy 3,4,5,etc...
`Sub Save_Workbook()
Const Path = "H:\HR\Cole G\Timehseet Test Path\"
Dim FileName As String
Dim Pos As Long
Pos = InStrRev(ActiveWorkbook.Name, ".") - 1
' If there wasn't a ".", then the file doesn't have an extension and Pos = -1
If Pos < 0 Then Pos = Len(ActiveWorkbook.Name)
' Now put everything together, including the file extension...
ActiveWorkbook.SaveAs Path & Left(ActiveWorkbook.Name, Pos) & Format (Now, "d-mm-yyyy") & Mid(ActiveWorkbook.Name, Pos + 1)
End Sub`
You could try a recursive approach like so (not tested):
Sub CreateCopyFile(ByVal oldFileName As String, Optional ByVal copyNo As Long = 1)
If FileLen(oldFileName & " Copy (" & copyNo & ")") Then
CreateCopyFile(oldFileName, copyNo + 1)
Else
ActiveWorkbook.SaveAs oldFileName & " Copy (" & copyNo & ")"
End If
End Sub
Then change your code to the following:
Dim potentialFileName As String
potentialFileName = Path & Left(ActiveWorkbook.Name, Pos) & Format(Now, "d-mm-yyyy") & Mid(ActiveWorkbook.Name, Pos + 1)
If FileLen(potentialFileName) Then
CreateCopyFile(potentialFileName)
Else
ActiveWorkbook.SaveAs potentialFileName
End If
'// rest of code here....
There used to be a cleaner way of doing this using a command prompt, however in recent years it seems that Windows no longer allows the use of it via VBA without changing security settings (which I do not advise...)
If Dir(Path & Left(ActiveWorkbook.Name, Pos) & Format (Now, "d-mm-yyyy") & Mid(ActiveWorkbook.Name, Pos + 1)) <> "" Then
ActiveWorkbook.SaveAs Filename:=Path & Left(ActiveWorkbook.Name, Pos) & copy 2 & Mid(ActiveWorkbook.Name, Pos + 1)
Else
ActiveWorkbook.SaveAs Filename:=Path & Left(ActiveWorkbook.Name, Pos) & Format (Now, "d-mm-yyyy") & Mid(ActiveWorkbook.Name, Pos + 1)
use this to save your file

Creating a macro that resets file and saves as new day

At work, I've been trying to create a macro that will automatically clear a certain range - only content -, the range being B78:G83.
After clearing this range, I'd like the macro to save the current file under a new name. The new name should be the current day, with format "dd mmmm" (two digits for the name, a space in between and then the full month's name)
The file path is (f.e.)
"T:\RESERVATIONS\Duty Report\2017\4. April\25 april"
with the year, month and current date being variable (as we make separate folders for these files at work).
Sub NieuweDag()
'
' NieuweDag Macro
' Invoer wissen en opslaan als nieuwe dag
'
' Sneltoets: Ctrl+q
'
Range("B78:G83").Select
Range("G82").Activate
Selection.ClearContents
Dim FilePath As String
Dim NewName As String
FilePath = "T:\RESERVATIONS\Duty Report\": NewName = FilePath & Year(Now()) & "\" & Month(Now()) & ". " & MonthName(Now()) & "\" & Format(Date, "dd mmmm") & ".xlsm"
ActiveWorkbook.SaveAs Filename:=NewName, FileFormat _
:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub
This is what I've got but it doesn't work. I get Error 5. It's in dutch, so allow me to translate:
Error 5 during launch:
Invalid procedure-call or invalid argument
Anyone out here be able to help me out?
The proper format is MonthName(number of month, [abbreviate]), you should use
MonthName(Month(Now()))
instead of
MonthName(Now())
Plus, you can enhance your code by using
Range("B78:G83").ClearContents
instead of
Range("B78:G83").Select
Range("G82").Activate
Selection.ClearContents
You can reduce the amount of coding required to create NewName by changing
NewName = FilePath & Year(Now()) & "\" & Month(Now()) & ". " & MonthName(Now()) & "\" & Format(Date, "dd mmmm") & ".xlsm"
to
NewName = FilePath & Format(Now(), "yyyy\\m. mmmm\\dd mmmm") & ".xlsm"

Correct Excel Macro to Save A Copy Excel File as TXT or CSV

So I have this home-made Excel Macro Template.
The task of the macro code that I inserted in my xlsm file is to Save a copy in the same folder with a different format. That format is .txt (see image below)
The expected result of the macro (after saving) should be the same with the excel file (visually) but this time it is in a .txt format.
Unfortunately, that didn't happened. It generates a different txt file and it contains unreadable alpha numeric characters, here's an example of the generated txt file.
¬TËNÃ0 ¼#ñ ‘¯(vဠjÚ # °µ· ©c[^SÚ¿g“–
P ö '±wfvìq 8o\1ÃD6øJœËž(Ðë`¬ŸTâõå¾¼ eð \ðX‰ ’ NOú/‹ˆTpµ§JÔ9Çk¥H×Ø É ÑóÌ8¤ 2 ¦‰Š §0AuÑë]* |FŸËÜbˆAÿ Çðîrq7çßK%#ëEq³\×RU btVCf¡jæ l¨ã±Õ(g#xJá
u j#XBG{Ð~J.Wr%WvŒTÛHgÜÓ †vf»ÜUÝ#ûœ¬Áâ R~€†›Rs§>BšŽB˜ÊÝ «žq®ÑIª ³l#§pçaä ý ë¿ î`ê*IuÃù ( ³´Ü ýÞð JŠ Át` “m'Ýû ™ ªîy¸„ f !å…C:r·KÐ}Ì5$4Ï9q Ž.à;ö. ¼] H ¼„ÿwá+mu S¶¸ŽÃ¦Ã¶fäÔ l;¶×‚A³ [u×Ðà ÿÿ PK ! µU0#ô L _rels/.rels ¢ (
Here's my macro code:
Sub SaveMe()
Dim FName As Range
Dim firstDate As String
Dim firstTime As String
Dim answer As Integer
firstDate = Format(Date, "mmddyyyy")
firstTime = Format(Now, "hhmmssAM/PM")
Set FName = Range("H5")
ActiveWorkbook.SaveCopyAs FileName:=ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".txt", FileFormat:=xlText, CreateBackup:=False
End Sub
I was wondering if anyone could take a look at my code and help to point out whats wrong.
It looks like you want the SaveAs Not the SaveCopyAs.
Fileformat xlText or xlTextMSDOS
You can two step the process. Save a copy, then open it, and save it as a text file.
ActiveWorkbook.SaveCopyAs FileName:=ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".xlsx"
Workbooks.Open (ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".xlsx")
ActiveWorkbook.SaveAs FileName:=ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".txt", FileFormat:=xlText, CreateBackup:=False
https://msdn.microsoft.com/en-us/library/office/ff841185.aspx
https://msdn.microsoft.com/en-us/library/office/ff198017.aspx
See from my post here. Excel VBA Export To Text File with Fixed Column Width + Specified Row and Columns Only + Transpose
Loop all rows and all cells. Send each value to a padspace function. Build the string from for each cells value with spaces padded after the cell value.
You will have to add a reference to you workbook. In the VBA IDE go to the tools pull down menu and select references. Then scroll down and select "Microsoft Scripting Runtime". Then hit OK.
Adjust the pad space function call argument to a number that fits the data that you have in your spreadsheet. So you will change the 20 in the line with the padspace call. PadSpace(20, len(cellValue))
This will do all rows and columns.
Public Sub MyMacro()
Dim lRow As Long
Dim lCol As Long
Dim strRow As String
Dim ws As Excel.Worksheet
Dim ts As TextStream
Dim fs As FileSystemObject
'Create the text file to write to
Set fs = New FileSystemObject
Set ts = fs.CreateTextFile("C:\Temp\test.txt", True, False)
Set ws = Application.ActiveSheet
'Loop through all the rows.
lRow = 1
Do While lRow <= ws.UsedRange.Rows.count
'Clear the string we are building
strRow = ""
'Loop through all the columns for the current row.
lCol = 1
Do While lCol <= ws.UsedRange.Columns.count
'Build a string to write out.
strRow = strRow & ws.Cells(lRow, lCol) & PadSpace(20, Len(ws.Cells(lRow, lCol)))
lCol = lCol + 1
Loop
'Write the line to the text file
ts.WriteLine strRow
lRow = lRow + 1
ws.Range("A" & lRow).Activate
Loop
ts.Close: Set ts = Nothing
Set fs = Nothing
End Sub
'This function will take the max number of spaces you want and the length of the string in the cell and return you the string of spaces to pad.
Public Function PadSpace(nMaxSpace As Integer, nNumSpace As Integer) As String
If nMaxSpace < nNumSpace Then
PadSpace = ""
Else
PadSpace = Space(nMaxSpace - nNumSpace)
End If
End Function