Deny Save As if cells do not have a value - excel

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

Related

Save the file to the corresponding folder based on month and year

I create a new file every day that is named based on the previous business day
It looks like "mmddyyyy ENCORE and Floor". It's a csv file and I need to convert it to xlsm
This code successfully saves my file with the correct name and file type but I need it to save to a different place on my computer with folders based on months:
ActiveWorkbook.SaveAs Filename:="C:\Users\Sarajevo2022\Downloads\" & _
Format(Evaluate("Workday(today(),-2)"), "mmddyyyy") & _
" ENCORE and Floor", FileFormat:=52
The correct file path looks like this:
C:\Users\Sarajevo2022\Company Name\Coworker - OCC ENCORE\2022\Dec 2022
Any direction?
Save As Macro-Enabled Workbook
Sub SaveAsMacroEnabled()
' Build the folder path.
Dim FolderLeft As String: FolderLeft = "C:\Users\Sarajevo2022"
' or:
'Dim FolderLeft As String: FolderLeft = Environ("USERPROFILE")
Dim FolderMid As String: FolderMid = "\Company Name\Coworker - OCC ENCORE\"
Dim SaveDate As Date: SaveDate = Application.WorkDay(Date, -2)
Dim FolderRight As String: FolderRight = Format(SaveDate, "yyyy") _
& "\" & UCase(Format(SaveDate, "mmm yyyy")) & "\"
Dim FolderPath As String: FolderPath = FolderLeft & FolderMid & FolderRight
' Check if the folder path exists.
Dim PathExists As Boolean
With CreateObject("Scripting.FileSystemObject")
PathExists = .FolderExists(FolderPath)
End With
If Not PathExists Then
MsgBox "The path '" & FolderPath & "' doesn't exist!" _
& vbLf & vbLf & "File not saved!", vbCritical
Exit Sub
End If
' Build the file path.
Dim FilePath As String: FilePath = FolderPath _
& Format(SaveDate, "mmddyyyy") & " ENCORE and Floor" & ".xlsm"
' Return the paths in the Immediate window (Ctrl+G).
Debug.Print FolderPath & vbLf & FilePath
' After you have confirmed that the paths are correct,
' out-comment the previous and uncomment the next line.
'ActiveWorkbook.SaveAs FilePath, xlOpenXMLWorkbookMacroEnabled ' or 52
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

Why is my code not duplicating ThisWorkbook and save it with a new incremental name (for the sake of version history)?

I'm trying to get a macro to work as a version history tool. I think I'm using basic methods here and there might be better ones out there but I think it's doable nonetheless. The error I get is "Subscript out of range". The culpript is the second to last line of my code, which is where I save a copy of the file. So this is my code:
Sub Historian()
Dim filePath As String
Static counter As Integer
Dim fileName As String
filePath = "A:\Downloads A\Ex_Files_Learning_VBA_Excel\Exercise Files\Ch05\WbkBackup"
For counter = 0 To 10
Workbooks.Open (filePath & counter)
On Error GoTo Handler:
Next counter
MsgBox ("counter has reached 10")
Exit Sub
Handler:
ThisWorkbook.Activate
fileName = ThisWorkbook.FullName
Workbooks(fileName).SaveCopyAs fileName:=(filePath & counter)
MsgBox ("ok, last version was: " & counter)
End Sub
Workbooks(filename) do not take the filename full path as argument, only the filename.
Change Workbooks(filename) to ThisWorkbook as suggested by Warcupine
To improve your code, I would suggest you not to test the opening of Workbook. This is long and then you have to close the workbooks you opened...
Instead you could use the Dir() function:
Check if the file exists using VBA
On Error GoTo Handler
should be placed before
Workbooks.Open (filePath & counter)
which should be:
Workbooks.Open (filePath & "\" & split(Thisworkbook.Name, ".")(0) & counter & "." & split(Thisworkbook.Name, ".")(1))
In fact, your code should look in this way:
Sub Historian()
Dim filePath As String, fileName As String, strExt As String
Static counter As Long
filePath = "C:\Teste VBA Excel\PROG BACKUP" ' "A:\Downloads A\Ex_Files_Learning_VBA_Excel\Exercise Files\Ch05\WbkBackup"
fileName = Split(ThisWorkbook.Name, ".")(0)
strExt = Split(ThisWorkbook.Name, ".")(1)
For counter = 0 To 10
On Error GoTo Handler:
Workbooks.Open (filePath & "\" & fileName & counter & "." & strExt)
Next counter
MsgBox ("counter has reached 10")
Exit Sub
Handler:
ThisWorkbook.SaveCopyAs fileName:=(filePath & "\" & fileName & counter & "." & strExt)
MsgBox ("ok, last version was: " & counter)
End Sub
But I think that checking the existing of the workbook by opening it, is not so appropriate way. I would suggest you to replace
On Error GoTo Handler:
Workbooks.Open (filePath & "\" & fileName & counter & "." & strExt)
with
If Dir(filePath & "\" & fileName & counter & "." & strExt) = "" Then GoTo Handler

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

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

Resources