Excel VBA Can't save file name with variable holding date value - excel

I have some code that copys and pastes the current worksheet to a blank new workbook, and then saves it depending on the values of some cells (stored in variables).
Specifically, these are Site, Client, and Date visited.
It all works fine with site and client, however when I include the date variable in the filename to save, it throws an error: Runtime error 76 - Path not found.
I'd appreciate any help/advise.
Sub Pastefile()
Dim client As String
Dim site As String
Dim visitdate As String
client = Range("B3").Value
site = Range("B23").Value
screeningdate = Range("B7").Value
Dim SrceFile
Dim DestFile
SrceFile = "C:\2013 Recieved Schedules\schedule template.xlsx"
DestFile = "C:\2013 Recieved Schedules" & "\" & client & " " & site & " " & visitdate & ".xlsx"
FileCopy SrceFile, DestFile
ActiveWindow.SmallScroll Down:=-12
Range("A1:I37").Select
Selection.Copy
ActiveWindow.SmallScroll Down:=-30
Workbooks.Open Filename:= _
"C:\Schedules\2013 Recieved Schedules" & "\" & client & " " & site & " " & visitdate & ".xlsx", UpdateLinks:= _
0
Range("A1:I37").PasteSpecial Paste:=xlPasteValues
Range("C6").Select
Application.CutCopyMode = False
ActiveWorkbook.Save
ActiveWindow.Close
End Sub

When using dates in file names, you never want to rely on the default textual representation of the date, because that depends on the current locale.
You should store the date as date in the first place, and explicitly format it in a safe way for the file name:
Dim visitdate As Date
visitdate = Range("b7").Value
dim visitdate_text as string
visitdate_text = Format$(visitdate, "yyyy\-mm\-dd")
You might also consider removing any special characters like \ from your other values, such as client and site. Otherwise the problem might arise again.

Here is my suggestion of code rewrite:
Sub Pastefile()
Dim client As String
Dim site As String
Dim visitdate As String
client = Range("B3").Value
site = Range("B23").Value
visitdate = Range("B7").Value
Dim SrceFile
Dim DestFile
If IsDate(visitdate) Then
SrceFile = "C:\2013 Received Schedules\schedule template.xlsx"
DestFile = "C:\2013 Received Schedules" & "\" & Trim(client) & " " & Trim(site) & " " & Str(Format(Now(), "yyyymmdd")) & ".xlsx"
If Trim(Dir("C:\2013 Received Schedules\schedule template.xlsx")) <> "" Then
FileCopy SrceFile, DestFile
Else
MsgBox (SrceFile & " is not available in the folder")
GoTo EndCode
End If
Range("A1:I37").Select
Selection.Copy
Workbooks.Open Filename:= _
"C:\Schedules\2013 Received Schedules" & "\" & client & " " & site & " " & visitdate & ".xlsx", UpdateLinks:= 0
Range("A1:I37").PasteSpecial Paste:=xlPasteValues
Range("C6").Select
Application.CutCopyMode = False
ActiveWorkbook.Save
ActiveWindow.Close
Else
MsgBox ("Please input the correct date in cell B7")
ActiveSheet.Range("B7").Activate
End If
EndCode:
End Sub

Related

How to save invoice created in excel using VBA

Save invoice that automate into folder according to month. Means that if the invoice date on 15 January 2023 so when it save will go to January folder not the other month such as May June etc.
Sub SaveInvoice()
Dim path As String
Dim MyFile As String path = "\\Japan\admin\Planning & Costing\Finance\Billing\DATA BILLING\IMPORT\2023\"
MyFile = Range("C13") & "_" & Range("H11") & "_" & Range("J13").Text 
'create invoice in XLSX format
ActiveWorkbook.SaveAs Filename:=path & MyFile & ".xls", FileFormat:=xlOpenXMLWorkbookMacroEnabled 
'ActiveWorkbook.Close
Application.DisplayAlerts = True 
MsgBox "Saving Complete! Thank you~" 
End Sub
Save File in Subfolders By Year and By Month
Sub SaveInvoice()
Const DST_INITIAL_PATH As String = "\\Japan\admin\" _
& "Planning & Costing\Finance\Billing\DATA BILLING\IMPORT\"
If Len(Dir(DST_INITIAL_PATH, vbDirectory)) = 0 Then
MsgBox "The initial path """ & DST_INITIAL_PATH & """doesn't exist.", _
vbCritical
Exit Sub
End If
Dim iDate As Date: iDate = Date ' today
Dim dPath As String: dPath = DST_INITIAL_PATH & Format(iDate, "yyyy") & "\"
If Len(Dir(dPath, vbDirectory)) = 0 Then MkDir dPath
dPath = dPath & Format(iDate, "mmmm") & "\"
If Len(Dir(dPath, vbDirectory)) = 0 Then MkDir dPath
Dim dws As Worksheet: Set dws = ActiveSheet ' improve!
Dim dFileName As String: dFileName = dws.Range("C13").Text _
& dws.Range("H11").Text & dws.Range("J13").Text & ".xlsx"
With dws.Parent
Application.DisplayAlerts = False ' to overwrite without confirmation
.SaveAs Filename:=dPath & dFileName, FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = True
.Close SaveChanges:=False
End With
MsgBox "Saving Complete! Thank you.", vbInformation
End Sub

VBA to save file in current folder with name from named ranges from file [duplicate]

I have some code that copys and pastes the current worksheet to a blank new workbook, and then saves it depending on the values of some cells (stored in variables).
Specifically, these are Site, Client, and Date visited.
It all works fine with site and client, however when I include the date variable in the filename to save, it throws an error: Runtime error 76 - Path not found.
I'd appreciate any help/advise.
Sub Pastefile()
Dim client As String
Dim site As String
Dim visitdate As String
client = Range("B3").Value
site = Range("B23").Value
screeningdate = Range("B7").Value
Dim SrceFile
Dim DestFile
SrceFile = "C:\2013 Recieved Schedules\schedule template.xlsx"
DestFile = "C:\2013 Recieved Schedules" & "\" & client & " " & site & " " & visitdate & ".xlsx"
FileCopy SrceFile, DestFile
ActiveWindow.SmallScroll Down:=-12
Range("A1:I37").Select
Selection.Copy
ActiveWindow.SmallScroll Down:=-30
Workbooks.Open Filename:= _
"C:\Schedules\2013 Recieved Schedules" & "\" & client & " " & site & " " & visitdate & ".xlsx", UpdateLinks:= _
0
Range("A1:I37").PasteSpecial Paste:=xlPasteValues
Range("C6").Select
Application.CutCopyMode = False
ActiveWorkbook.Save
ActiveWindow.Close
End Sub
When using dates in file names, you never want to rely on the default textual representation of the date, because that depends on the current locale.
You should store the date as date in the first place, and explicitly format it in a safe way for the file name:
Dim visitdate As Date
visitdate = Range("b7").Value
dim visitdate_text as string
visitdate_text = Format$(visitdate, "yyyy\-mm\-dd")
You might also consider removing any special characters like \ from your other values, such as client and site. Otherwise the problem might arise again.
Here is my suggestion of code rewrite:
Sub Pastefile()
Dim client As String
Dim site As String
Dim visitdate As String
client = Range("B3").Value
site = Range("B23").Value
visitdate = Range("B7").Value
Dim SrceFile
Dim DestFile
If IsDate(visitdate) Then
SrceFile = "C:\2013 Received Schedules\schedule template.xlsx"
DestFile = "C:\2013 Received Schedules" & "\" & Trim(client) & " " & Trim(site) & " " & Str(Format(Now(), "yyyymmdd")) & ".xlsx"
If Trim(Dir("C:\2013 Received Schedules\schedule template.xlsx")) <> "" Then
FileCopy SrceFile, DestFile
Else
MsgBox (SrceFile & " is not available in the folder")
GoTo EndCode
End If
Range("A1:I37").Select
Selection.Copy
Workbooks.Open Filename:= _
"C:\Schedules\2013 Received Schedules" & "\" & client & " " & site & " " & visitdate & ".xlsx", UpdateLinks:= 0
Range("A1:I37").PasteSpecial Paste:=xlPasteValues
Range("C6").Select
Application.CutCopyMode = False
ActiveWorkbook.Save
ActiveWindow.Close
Else
MsgBox ("Please input the correct date in cell B7")
ActiveSheet.Range("B7").Activate
End If
EndCode:
End Sub

Loop to save worksheet in new workbook

I want to run through a specific sheet (from & to) save those ws as a new file in a folder, if the folder doesn't exist then create.
I'm able to do it to one sheet.
ActiveSheet.Next.Select
If Range("F3").Value = "" Then
Windows("Import OT.xlsm").Activate
Sheets("Cash").Select
Dim filename101 As String
Dim path101 As String
Application.DisplayAlerts = False
path101 = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
filename101 = Range("B1").Value & ".xlsx"
ActiveWorkbook.SaveAs path101 & Range("A2") & "\" & Range("A1") & " " & filename101,xlOpenXMLWorkbook
Application.DisplayAlerts = True
Else
Cells.Select
Range("F3").Activate
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Dim Path1 As String
Dim fpathname1 As String
Path1 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\"
fpathname1 = Path1 & Range("F3") & "\" & Range("F2") & " " & Range("B3") & ".xlsx"
path01 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & Range("F3")
Dim path001 As String
Dim Folder As String
Folder = Dir(path01, vbDirectory)
If Folder = vbNullString Then
VBA.FileSystem.MkDir (path01)
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
Else
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
End If
End If
End Sub
I want this as a loop is because I have a few tens of sheets. For it to work I think I need to write it specific time, but with loop I learned I don't need to do that.
Excel file sheet
https://onedrive.live.com/view.aspx?resid=AF6FF2618C09AC74!29027&ithint=file%2cxlsx&authkey=!AHcJjYCu8D0NTNY
According to your comment where you wrote the steps:
Read the comments
Try to run the code using F8 key and see where you need to change it.
As you're learning, please note to first write the steps in plain English Norsk and then develop your code.
See how I just followed your steps with readable code.
Code:
Public Sub GenerateCustomersFiles()
' 1) Active sheet (oppgjør 1-20)
Dim targetSheet As Worksheet
For Each targetSheet In ThisWorkbook.Sheets
' Check only sheets with string in name
If InStr(targetSheet.Name, "Oppgjør") > 0 Then
' 2) look if value in F3 is empty
If targetSheet.Range("F3").Value = vbNullString Then
' 3) if it is, do select "cash" sheet and save this file (its name and path are given above what it should be named)
Dim fileName As String
Dim filePath As String
Dim folderPath As String
folderPath = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
fileName = targetSheet.Range("B1").Value & ".xlsx"
filePath = folderPath & targetSheet.Range("A2") & "\" & targetSheet.Range("A1") & " " & fileName
ThisWorkbook.Worksheets("Cash").Select
ThisWorkbook.SaveAs filePath, xlOpenXMLWorkbook
Else
' 4) if it doesn't, do open selected sheet to a new workbook and save that in clients name folder (folder and path given above in code section)
folderPath = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & targetSheet.Range("F3")
fileName = targetSheet.Range("F2") & " " & targetSheet.Range("B3") & ".xlsx"
filePath = folderPath & "\" & fileName
' 5) check if clients folder exist or not for the file to be saved in.
' if folder doesnt exist,
' create new and save file there.
CreateFoldersInPath folderPath
' if folder exist just save the file there
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Add
targetSheet.Copy before:=targetWorkbook.Sheets(1)
targetWorkbook.SaveAs filePath, 51
targetWorkbook.Close
End If
End If
Next targetSheet
End Sub
' Credits: https://stackoverflow.com/a/31034201/1521579
Private Sub CreateFoldersInPath(ByVal targetFolderPath As String)
Dim strBuildPath As String
Dim varFolder As Variant
If Right(targetFolderPath, 1) = "\" Then targetFolderPath = Left(targetFolderPath, Len(targetFolderPath) - 1)
For Each varFolder In Split(targetFolderPath, "\")
If Len(strBuildPath) = 0 Then
strBuildPath = varFolder & "\"
Else
strBuildPath = strBuildPath & varFolder & "\"
End If
If Len(Dir(strBuildPath, vbDirectory)) = 0 Then MkDir strBuildPath
Next varFolder
'The full folder path has been created regardless of nested subdirectories
'Continue with your code here
End Sub
Let me know how it goes

End AfterSave event from different macro

I am trying to create a macro that, upon save, asks the user if the file they are working is the final version. If it is, I would like to save a copy of that file in a different destination. It also creates an indicator with the username and date saved of the final copy so that if a user tries to create ANOTHER final copy, it asks them if they would like to overwrite the version created by [username] on [date].
I decided to use AfterSave as opposed to BeforeSave, as I would like the user to have the option of choosing between Save and SaveAs before the macro runs.
The issue that I am having is that if the user indicates that it is the final version, a copy is saved, triggering the AfterSave event. Is there a line of code I can add that would stop the AfterSave event after the file copy is saved?
Here is my current code.
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
If Success Then
Call YesNoMessageBox
End If
End Sub
'Saves copy of tool if final version
Sub YesNoMessageBox()
Dim Answer1 As String
Dim MyNote1 As String
Dim fileName As String
Dim dlgOpen As FileDialog
Dim MyYear
Dim FilePath
Dim Answer2 As String
Dim MyNote2 As String
MyNote1 = "Is this the FINAL version?"
'Display MessageBox
Answer1 = MsgBox(MyNote1, vbQuestion + vbYesNo, "???")
If Answer1 = vbYes Then
If Not Worksheets("Data Input").Range("M2") = vbNullString Then
MyNote2 = "There is already a version saved by " & Worksheets("Data Input").Range("M2") & " on " & Worksheets("Data Input").Range("M3") & "." & vbNewLine & "Would you like to overwrite it?"
Answer2 = MsgBox(MyNote2, vbQuestion + vbYesNo, "???")
If Answer2 = vbYes Then
strUName = CreateObject("WScript.Network").UserName
Worksheets("Data Input").Range("M2") = strUName
Worksheets("Data Input").Range("M3") = Date
'Saves copy of tool in [folder name] folder
MyYear = Year(Worksheets("Data Input").Range("D13"))
ThisWorkbook.SaveAs fileName:="G:\[file path]" & Worksheets("Data Input").Range("D9") & " - " & Worksheets("Data Input").Range("D7") & " " & MyYear & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
MsgBox "Copy of tool saved in" & Application.ThisWorkbook.Path
End If
Else
strUName = CreateObject("WScript.Network").UserName
Worksheets("Data Input").Range("M2") = strUName
Worksheets("Data Input").Range("M3") = Date
'Saves copy of tool in [folder name]folder
MyYear = Year(Worksheets("Data Input").Range("D13"))
ThisWorkbook.SaveAs fileName:="G:\[File Path]\" & Worksheets("Data Input").Range("D9") & " - " & Worksheets("Data Input").Range("D7") & " " & MyYear & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
MsgBox "Copy of tool saved in" & Application.ThisWorkbook.Path
End If
End If
End Sub
Disable events before the SaveAs but don't forget to enable again after:
Application.EnableEvents = False
ThisWorkbook.SaveAs fileName:="G:\[File Path]\" & Worksheets("Data Input").Range("D9") & " - " & Worksheets("Data Input").Range("D7") & " " & MyYear & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Application.EnableEvents = True

Deny Save As if cells do not have a value

I have a script that is used to save an excel template based on the contents of two cells/named ranges (FailReportSN and FailReportDD). My issue is that the end users do not always remember to enter values into those two cells before running the save as script below. What I need to do is modify my current script to only save if there are values in both cells.
Sub saveAsFATPMM()
Dim PathMac As String, Path As String, FolderPath As String
If Application.PathSeparator = ":" Then
FolderPath = "Volumes:Server:Groups:METI:Quality Control:METIman:"
PathMac = FolderPath & Sheets("Failure Report").Range("FailReportSN").Text & _
" - FATP - " & Sheets("Failure Report").Range("FailReportDD").Text & ".xlsm"
'Format(Date, "mm-dd-yy")
ThisWorkbook.SaveAs Filename:=PathMac, FileFormat:=53, CreateBackup:=True
Else
FolderPath = "\\server\server\Groups\METI\Quality Control\METIman\"
Path = FolderPath & Sheets("Failure Report").Range("FailReportSN").Text & _
" - FATP - " & Sheets("Failure Report").Range("FailReportDD").Text & ".xlsm"
'Format(Date, "mm-dd-yy")
ThisWorkbook.SaveAs Filename:=Path, FileFormat:=52, CreateBackup:=True
End If
MsgBox "Your file has been saved. Thank you."
End Sub
Use conditional If to check for those values first. In the code below I check to make sure the Len of that Range is not 0 (or False in this case, since 0 equates to False here). I also refactored a bit to get rid of essentially duplicate code.
Sub saveAsFATPMM()
With Sheets("Failure Report")
If Len(.Range("FailReportSN")) And Len(.Range("FailReportDD")) Then
Dim PathMac As String, Path As String, FolderPath As String, fFormat as Long
If Application.PathSeparator = ":" Then
FolderPath = "Volumes:Server:Groups:METI:Quality Control:METIman:"
fFormat = 53
Else
FolderPath = "\\server\server\Groups\METI\Quality Control\METIman\"
fFormat = 52
End If
Path = FolderPath & .Range("FailReportSN").Text & _
" - FATP - " & .Range("FailReportDD").Text & ".xlsm"
ThisWorkbook.SaveAs Filename:=Path, FileFormat:=fFormat, CreateBackup:=True
MsgBox "Your file has been saved. Thank you."
Else
MsgBox "File not saved! Enter Fail Report Values and Try Again!"
End If
End With
End Sub

Resources