Variable not being consistant in excel vba macro - excel

I have a macro in excel that if a drive exists the macro saves the file to my harddrive and thumbdrive. If it doesn't exist, it saves to the harddrive. When the macro runs I am getting an error. Here is the macro:
Sub SaveFile()
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
Dim filepath As String
name = "Siemens"
filepath = "F:\Dave backup\Open Orders\Label Manifests\Active Labels Manifest\Manifest Related\File saving testing folder\" & name & "\" & name & " Manifest " & Format(Now, "mm-dd-yyyy")
If fso.DriveExists("F:\") = True Then
'ActiveWorkbook.SaveAs filename:="C:\Users\dgray\Documents\" & name & " Manifest " & Format(Now, "mm-dd-yyyy")
'ActiveWorkbook.SaveAs filename:="F:\Dave backup\Open Orders\" & name & "\" & name & " Manifest " & Format(Now, "mm-dd-yyyy")
ActiveWorkbook.SaveAs filename:=filepath
Else
'ActiveWorkbook.SaveAs filename:="C:\Users\dgray\Documents\" & name & " Manifest " & Format(Now, "mm-dd-yyyy")
ActiveWorkbook.SaveAs filename:="F:\Dave backup\Open Orders\Label Manifests\Active Labels Manifest\Manifest Related\File saving testing folder\" & name & "\" & name & " Manifest " & Format(Now, "mm-dd-yyyy")
End If
End Sub
Here is the error I am getting:
I don't know if you can see but the last part of the error message says "\Siemens\8E555720. That should also say the customer name (i.e. Siemens). In the code I have set the customer name in the variable "name". So why is it giving me this crazy error? All help is appreciated.

Something like this might be better:
Sub SaveFile()
Const PATH_C As String = "C:\Users\dgray\Documents\"
Const PATH_F As String = "F:\Dave backup\Open Orders\Label Manifests\" & _
"Active Labels Manifest\Manifest Related\File saving testing folder\"
Dim fileName As String, custName As String
custName = "Siemens"
fileName = custName & " Manifest " & Format(Now, "mm-dd-yyyy") & ".xlsx" 'or .xlsm
ActiveWorkbook.SaveAs fileName:=PATH_C & fileName 'assume C is always available
'save to F if available
If Len(Dir(PATH_F)) > 0 Then
'assumes the custName folder already exists...
ActiveWorkbook.SaveAs fileName:=PATH_F & custName & "\" & fileName
End If
End Sub

I can see the space in folder name which may cause this error.
By removing space in the foldername this error would be fixed.

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

Using the Current Month in a Folder Path in VBA Code

When I run this code I get an error message
"compile error: named argument not found".
Sub SavetoCurrentMonth()
Application.DisplayAlerts = False
' Check for month folder and create if needed
If Len(Dir("C:\Users\OsmonBek\Documents\macros test\" & Format(Month(Date), "P00-") & Format(Date, "mmmm"), vbDirectory)) = 0 Then
MkDir "C:\Users\OsmonBek\Documents\macros test\" & Format(Month(Date), "P00-") & Format(Date, "mmmm")
End If
' Save File
ActiveWorkbook.ExportAsFixedFormat Filename:= _
"C:\Users\OsmonBek\Documents\macros test\" & MonthName(Month(Date), False) & "\" & Format(Date, "mm.dd.yy") & ".xlsx" _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Application.DisplayAlerts = True
' Popup Message
MsgBox "File Saved As:" & vbNewLine & "C:\Users\OsmonBek\Documents\macros test\" & MonthName(Month(Date), False) & "\" & Format(Date, "mm.dd.yy") & ".xlsx"
End Sub
The error was telling you that ExportAsFixedFormat doesn't have a parameter called FileFormat.
I'd use something like this function to return the name of the folder for the current month (creating the folder if it doesn't already exist) like c:\P2022_04\.
Function getMonthFolderPath() As String
'creates/returns folder name for current month, like: c:\P2022_04\
Const basePath = "c:\", prefix = "P"
Dim path As String
path = basePath & prefix & Format(Date, "yyyy_mm")
If Dir(path, vbDirectory) = "" Then MkDir path
getMonthFolderPath = path & "\"
End Function
I added the year since (I assume) you don't all April's in the same folder.
Here's a variation that will (if needed) create a year folder with a month subfolder, and return that path:
Function getMonthFolderPath() As String
Dim path As String
path = "c:\"
path = path & Year(Date)
If Dir(path, vbDirectory) = "" Then MkDir path
path = path & "\" & Format(Date, "mm")
If Dir(path, vbDirectory) = "" Then MkDir path
getMonthFolderPath = path & "\"
End Function
Either variation could be used to save the current file, like this:
Sub saveDemo()
'save this workbook like: C:\2022\04\2022-04-08.xlsm
Dim fName As String
fName = getMonthFolderPath & Format(Date, "yyyy-mm-dd") & ".xlsm"
Application.DisplayAlerts = False 'ignore overwrite warning
ThisWorkbook.SaveAs fName, xlOpenXMLWorkbookMacroEnabled
Application.DisplayAlerts = True
End Sub

Attach certain files

I want to build the following:
select sheets for pdf printing - works
create folder and print sheets - works
attach those printed files to an email - doesn't work
the filename depends on cell values + Date (last Range.Value in filename), is there a way to get those pdfs attached?
I tried the following, but that doesn't work
'code ...
Dim myDir as String, mySht as String
myDir = "C:\Users\ihlin\OneDrive\Düngung\" & Worksheets("Drip_Drain_Eingabe").Range("s13").Text
mySht = Worksheets("Druckansicht_mmol").Range("c2").Text & "_" & Worksheets("Druckansicht_mmol").Range("K2").Text & "_" & Worksheets("Druckansicht_mmol").Range("P2").Text & "_" & "mmol_" & Worksheets("Druckansicht_mmol").Range("T1").Text
`code ... ...
If CheckBox1 = True Then
.Attachments.Add myDir & "\" & mySht & ".pdf"
End if
If CheckBox2 = True Then
.Attachments.Add myDir & "\" & mySht2 & ".pdf"
If CheckBox1 = True Then
.Attachments.Add myDir & "\" & mySht3 & ".pdf"
End if
If CheckBox1 = True Then
.Attachments.Add myDir & "\" & mySht4 & ".pdf"
End if
Publishing takes forever and ends with crashing Excel.
Any help would be appreciated.
Here is a simple debugging method. Try the following:
.Attachments.Add "c:\somehardcoded\address\ofthe\worksheet\folder\file.pdf"
If it works, then super, you simply have to find a way to represent the folder.
If it does not work, then forget it and try to attach the file in another way.

VBA way to manually save the excel file based on 'dynamic' parameters passed.

I have created an application using excel macro, where the user feeds certain values and saves it to several directory path with a button click macro.
When I select a region from drop down, it should save the file to designated region folder. Say for eg, when NY is selected, the file will be saved to shared drive and 2016 - NY folder. But now, deciding the future of the application, I am thinking of having "year" as a separate field in the worksheet, which retrieves the year value from the user. How do I achieve this without the necessity to change the code every year. The process will be continuing for 'n' number of years from now. Thanks in Advance !
FileName1 = Range("D3").Value
filenameOfNewBook = FileName1
If location = "Illinois" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\Illinois\" & FileName1 & "-" & "checklist" & ".xlsm"
ElseIf location = "LA" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\LA\" & FileName1 & "-" & "checklist" & ".xlsm"
ElseIf location = "NY" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\NY\" & FileName1 & "-" & "checklist" & ".xlsm"
Else
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\Atlanta\" & FileName1 & "-" & "checklist" & ".xlsm"
End If
MsgBox "File Saved successfully!", , "Save"
ActiveWorkbook.save
Application.DisplayAlerts = True
From my experience for office tasks purpose, it's better not to refer to current year, but year set by user, so for example in January 2017 user can still perform actions on files related to 2016. You can get rid of the following:
If location = "Illinois" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\Illinois\" & FileName1 & "-" & "checklist" & ".xlsm"
ElseIf location = "LA" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\LA\" & FileName1 & "-" & "checklist" & ".xlsm"
ElseIf location = "NY" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\NY\" & FileName1 & "-" & "checklist" & ".xlsm"
Else
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\Atlanta\" & FileName1 & "-" & "checklist" & ".xlsm"
End If
And instead use:
Dim myYear as String, locations() as String, locationForPath as String
Dim locCounter as Long
myYear = ThisWorkbook.Worksheets("Sheet1").Range("a2").value2 'the cell with year value, for example 2016
locations = Split("Illinois,LA,NY",",")
For locCounter = LBound(locations) to UBound(locations)
If location = locations(locCounter) Then locationForPath = location: Exit For
Next locCounter
If locationForPath = vbNullString Then locationForPath = "Atlanta"
ActiveWorkbook.SaveAs FileName:="W:\Audits\" & myYear & "\" & locationForPath & "\" & FileName1 & "-" & "checklist" & ".xlsm"

Save the worksheet and delete file button

I have the following question. I use a file to log assets (laptops, desktops etc) into certain folders, like deployed, stock, repair and hotswap.
I made some buttons in it which work all fine. One button called deployed, when I save the sheet with this button it saves it with EU IMAC, serial number and date as XLMS file.
I like to change the code from this button, so that when I save a sheet as deployed it automatically delete the XLMS file with serial number and name in the folder stock.
Below the codes for all the save buttons and it's button 61 that needs to be fixed, the others I will change afterwards. The code is form other forum, but with no success.
Sub Button60_Click()
Range("A1:G68").PrintOut
End Sub
Sub Button51_Click()
ActiveWorkbook.SaveAs "C:\Users\rjbakkex\Documents\Assets_logging\Hotswap\" & Format(ActiveWorkbook.Worksheets("EU IMAC").Range("B26").Value) & " - Hotswap -" & Format(Date, "yyyy-mm-dd") & ".xlsm"
End Sub
Sub Button53_Click()
ActiveWorkbook.SaveAs "C:\Users\rjbakkex\Documents\Assets_logging\Returned to stock\" & Format(ActiveWorkbook.Worksheets("EU IMAC").Range("B26").Value) & " - Return to stock - " & Format(Date, "yyyy-mm-dd") & ".xlsm"
End Sub
Sub awaitwuhan_Click()
ActiveWorkbook.SaveAs "C:\Users\rjbakkex\Documents\Assets_logging\To repair\" & Format(ActiveWorkbook.Worksheets("EU IMAC").Range("B26").Value) & "- Repair -" & Format(Date, "yyyy-mm-dd") & ".xlsm"
End Sub
Sub Button61_Click()
p = "C:\Users\rjbakkex\Documents\Assets_logging\Deployed\"
'opslaan
s_name = Sheets("EU IMAC").Range("B25").Value & " - Deployed -" & Format(Date, "yyyy-mm-dd") & ".xlsm"
ActiveWorkbook.SaveAs p & s_name
'verwijderen
d_name = Sheets("EU IMAC").Range("B25").Value & " - Return to stock -" & Format(Date, "yyyy-mm-dd") & ".xlsm"
If MsgBox("Are you sure that you want to remove " & d_name & " from the system?", vbQuestion + vbYesNo, "Sure?") = vbYes Then Kill p & d_name
End Sub
First, give your buttons meaningful names, that is such a garbled mess to try and determine what button60 is or does.
Second You need to use the file system object from Microsoft Scripting Library (add a reference in excel to this dll scrrun.dll) then you can check to see if the file exists and delete it
Sub Button61_Click()
p = "C:\Users\rjbakkex\Documents\Assets_logging\Deployed\"
'opslaan
s_name = Sheets("EU IMAC").Range("B25").Value & " - Deployed -" & Format(Date, "yyyy-mm-dd") & ".xlsm"
ActiveWorkbook.SaveAs p & s_name
'verwijderen
d_name = Sheets("EU IMAC").Range("B25").Value & " - Return to stock -" & Format(Date, "yyyy-mm-dd") & ".xlsm"
'create the file system object
Dim fso As FileSystemObject
Set fso = New FileSystemObject
'make sure the file exists first
If fso.FileExists(p & d_name) = True Then
If MsgBox("Are you sure that you want to remove " & d_name & " from the system?", vbQuestion + vbYesNo, "Sure?") = vbYes Then
fso.DeleteFile p & d_name, True
End If
End If
'free the memory
Set fso = Nothing
End Sub

Resources