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
So i have found 2 macros which i want to use to save and create a back up files for the said file.
The Macro which i want to primarily use is this one:
Sub DateFolderSave()
Dim strGenericFilePath As String: strGenericFilePath = "D:\"
Dim strYear As String: strYear = Year(Date) & "\"
Dim strMonth As String: strMonth = MonthName(Month(Date)) & "\"
Dim strDay As String: strDay = Day(Date) & "\"
Dim strFileName As String: strFileName = "_Dispatch Process_"
Application.DisplayAlerts = False
' Check for year folder and create if needed
If Len(Dir(strGenericFilePath & strYear, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear
End If
' Check for month folder and create if needed
If Len(Dir(strGenericFilePath & strYear & strMonth, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear & strMonth
End If
' Check for date folder and create if needed
If Len(Dir(strGenericFilePath & strYear & strMonth & strDay, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear & strMonth & strDay
End If
' Save File
ActiveWorkbook.SaveAs FileName:= _
strGenericFilePath & strYear & strMonth & strDay & strFileName, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Application.DisplayAlerts = True
' Popup Message
MsgBox "File Saved As: " & vbNewLine & strGenericFilePath & strYear & strMonth & strDay & strFileName
End Sub
So i found this another Macro which make continuous back up of the files and has a custom format to a file name
Sub Save_Backup(ByVal Backup_Folder_Path As String)
Dim fso As Object
Dim ExtensionName As String, FileName As String
Dim wbSource As Workbook
Set fso = CreateObject("Scripting.FileSystemObject")
Set wbSource = ThisWorkbook
ExtensionName = fso.GetExtensionName(wbSource.Name)
FileName = Replace(wbSource.Name, "." & ExtensionName, "")
fso.CopyFile ThisWorkbook.FullName, _
fso.BuildPath(Backup_Folder_Path, FileName & " (" & Format(Now(), "dd-mmm-yy hh.mm AM/PM") & ")." & ExtensionName)
Set fso = Nothing
Set wbSource = Nothing
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Call Save_Backup("C:\Users\admin\Downloads\Back Up\New Backup")
End Sub
So i want to create back up like the first macro(i.e. Folder inside a folders for the specific date) but want to have a continuous stream of files for back up(i.e. Want the date folder to create new save file each time i save the Document)
Is there a way to combine both these macros?
I am a newbie in excel vba coding and trying to create pdf of a excel sheet range. My code works well in windows OS but somehow it doesn't work in Mac OS. The Code is as below:
`
Sub GeneratePDF()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim VelleName As String
Dim SelectedRange As Range
With ThisWorkbook.Worksheets("modulo")
.Activate
.Range(.Cells(1, 1), .Cells(33, 10)).Select
Selection.Name = "SelectedRange"
End With
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveWorkbook.Worksheets("modulo")
strTime = Format(Now(), "ddmmyyyy\_hhmm")
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
VelleName = ThisWorkbook.Worksheets("database").Range("B" & Desiredrow) & "_" & ThisWorkbook.Worksheets("database").Range("C" & Desiredrow)
'replace spaces and periods in sheet name
strName = Replace(VelleName, " ", "_")
strName = Replace(strName, ".", "_")
strName = Replace(strName, "-", "_")
strName = Replace(strName, "/", "_")
'create default name for savng file
strFile = strName & "_" & strTime & ".pdf"
strPathFile = strName & "_" & strTime
' select folder for file
If Dir(strPath & Application.PathSeparator & "forme", vbDirectory) = "" Then '<== check if folder exists but its not detecting even though i had created a folder there.
MkDir (ThisWorkbook.Path & Application.PathSeparator & "forme") '<== Create Folder and its not working for Mac OS.
End If
myFile = ThisWorkbook.Path & Application.PathSeparator & "forme" & Application.PathSeparator & strPathFile
'export to PDF if a folder was selected
If myFile <> "False" Then
With wsA.PageSetup
.Orientation = xlPortrait
.PrintArea = "SelectedRange"
.Zoom = False
.FitToPagesTall = 1
.FitToPagesWide = 1
End With
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "Il file pdf è stato creato: " _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Impossibile creare il file pdf"
Resume exitHandler
End Sub
`
I have tried searching a lot on internet but havent found any source which specifically teaches vba coding in Mac OS. Moreover, i got only one link https://macexcel.com/examples/filesandfolders/makefolder/ but i dont think it would work as it should be only one line of command and the biggest issue i dont have Mac OS available now. So can somebody test my code change my command to make it compatible it with Mac OS
I used to use this code and also add to check file exist
'Only Change code Here
Sub Verify()
Dim myPath As String
myPath = "C:\abc" '<--------This line
If Not PathExist(myPath) Then MkDir (myPath)
End Sub
Private Function PathExist(path_ As String) As Boolean
On Error GoTo ErrNotExist
Call ChDir(path_)
PathExist = True
Exit Function
ErrNotExist:
PathExist = False
End Function
Private Function FileExist(filePath_ As String) As Boolean
FileExist = Len(Dir(filePath_)) <> 0
End Function
I need to modify this code to first search if a file exists, if so, do nothing but show a message, if not, the code below will automatically create the file. Thanks in advance.
Option Explicit
Public WithEvents MonitorApp As Application
Private Sub Workbook_Open()
Dim strGenericFilePath As String: strGenericFilePath = "\\Server2016\Common\Register\"
Dim strYear As String: strYear = Year(Date) & "\"
Dim strMonth As String: strMonth = MonthName(Month(Date)) & "\"
Dim strFileName As String: strFileName = "Register Sheet " & Format(Date, "mmm dd yyyy")
Application.DisplayAlerts = False
If Len(Dir(strGenericFilePath & strYear, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear
End If
If Len(Dir(strGenericFilePath & strYear & strMonth, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear & strMonth
End If
If Len(Dir(strGenericFilePath & strYear & strMonth, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear & strMonth
End If
ActiveWorkbook.SaveAs Filename:= strGenericFilePath & strYear & strMonth & strFileName, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Application.DisplayAlerts = True
MsgBox "File Saved As: " & vbNewLine & strGenericFilePath & strYear & strMonth & strFileName
End Sub
This is the entire code that goes from importing an Excel document to creating folders using an Excel spreadsheet.
Sub Update_JL()
Dim wsJL As Worksheet 'Open Orders
Dim wsJOD As Worksheet 'Jobs Data
Dim wsJAR As Worksheet 'JL Archive
Dim wbBK1 As Workbook
Dim wbBK2 As Workbook
Dim wsBOR As Worksheet
Dim lastrow As Long, fstcell As Long, strCompany As String, strPart As String, strPath As String, strFile As String
Dim cell As Range, newFolder As String, PhotoDir As String
Set wsJL = Sheets("Open Orders")
Set wsJOD = Sheets("Jobs Data")
Set wsJAR = Sheets("JL Archive")
Set wbBK1 = ThisWorkbook
Set wbBK2 = ActiveWorkbook
Application.ScreenUpdating = False ' Prevents screen refreshing.
Application.Calculation = xlCalculationManual
With wsJOD
.Columns("A:Q").Clear
wsJL.Range("B2:I2").Copy wsJOD.Range("A1")
.Range("I1").Formula = "=COUNTIFS('Open Orders'!$B:$B,$A1,'Open Orders'!$D:$D,$C1)"
.Range("J1").Formula = "=IF(I1,""Same"",""Different"")"
End With
strFile = Application.GetOpenFilename()
Set wbBK2 = Application.Workbooks.Open(strFile)
Set wsBOR = Sheets(Replace(wbBK2.Name, ".csv", ""))
lastrow = wsBOR.Range("C" & Rows.Count).End(xlUp).Row
wsBOR.Range("B6:E" & lastrow).Copy wsJOD.Range("A2")
wsBOR.Range("G6:H" & lastrow).Copy wsJOD.Range("E2")
wsBOR.Range("L6:L" & lastrow).Copy wsJOD.Range("G2")
wsBOR.Range("N6:N" & lastrow).Copy wsJOD.Range("H2")
wbBK2.Close
lastrow = wsJOD.Range("A" & Rows.Count).End(xlUp).Row
wsJOD.Range("I1:J1").Copy wsJOD.Range("I2:J" & lastrow)
wsJOD.Range("I2:J" & lastrow).Calculate
lastrow = wsJL.Range("B" & Rows.Count).End(xlUp).Row
wsJL.Range("P2:R2").Copy wsJL.Range("P3:R" & lastrow)
wsJL.Range("P3:R" & lastrow).Calculate
With Intersect(wsJL.UsedRange, wsJL.Columns("Q"))
.AutoFilter 1, "<>Same"
With Intersect(.Offset(2).EntireRow, .Parent.Range("B:U"))
.Copy wsJAR.Cells(Rows.Count, "B").End(xlUp).Offset(1)
.EntireRow.Delete
End With
.AutoFilter
End With
lastrow = wsJOD.Range("A" & Rows.Count).End(xlUp).Row
With Intersect(wsJOD.UsedRange, wsJOD.Range("J2:J" & lastrow))
.AutoFilter 1, "<>Different"
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
wsJOD.Range("A2:H" & lastrow).Copy wsJL.Cells(Rows.Count, "B").End(xlUp).Offset(1)
wsJOD.Columns("A:Q").Clear
lastrow = wsJL.Range("B" & Rows.Count).End(xlUp).Row
wsJL.Range("J3:K3").Copy wsJL.Range("J4:K" & lastrow)
wsJL.Range("B3:N3").Copy
wsJL.Range("B4:N" & lastrow).Borders.Weight = xlThin
wsJL.Range("B4:N" & lastrow).Font.Size = 11
wsJL.Range("B4:N" & lastrow).Font.Name = "Calibri"
wsJL.Range("J3:K" & lastrow).Calculate
'Sort PO Tracking
With wsJL
.Sort.SortFields.Clear
'Sort Reds
.Sort.SortFields.Add(.Range("K3:K" & lastrow), _
xlSortOnIcon, xlAscending, , xlSortNormal).SetIcon Icon:=ActiveWorkbook. _
IconSets(4).Item(1)
.Sort.SortFields.Add Key:=Range( _
"K3:K" & lastrow), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
'Sort Yellows
.Sort.SortFields.Add(.Range("J3:J" & lastrow), _
xlSortOnIcon, xlAscending, , xlSortNormal).SetIcon Icon:=ActiveWorkbook. _
IconSets(4).Item(2)
'Sort Greens
.Sort.SortFields.Add(.Range("J3:J" & lastrow), _
xlSortOnIcon, xlAscending, , xlSortNormal).SetIcon Icon:=ActiveWorkbook. _
IconSets(4).Item(3)
.Sort.SortFields.Add Key:=Range( _
"J3:J" & lastrow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With .Sort
.SetRange wsJL.Range("B2:U" & lastrow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
lastrow = wsJL.Range("B" & Rows.Count).End(xlUp).Row
wsJL.Range("B3:N" & lastrow).Select
wsJL.Range("B3:N" & lastrow).VerticalAlignment = xlCenter
wsJL.Range("A1").Select
End With
With wsJL
strCompany = CleanName(Range("C3")) ' assumes company name starts in C
strPart = CleanName(Range("D3")) ' assumes part in D
strPath = wbBK1.path & Application.PathSeparator & "Photos" & Application.PathSeparator
If Not FolderExists(strPath & strCompany) Then
'company doesn't exist, so create full path
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strCompany & Application.PathSeparator & strPart) Then
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
End If
End If
Range("J:M").Calculate
End With
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
MsgBox "Open Orders Updated!"
End Sub
The functions:
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim fso As New FileSystemObject
If FolderExists(path) Then
Exit Function
Else
On Error GoTo DeadInTheWater
fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
Exit Function
End If
DeadInTheWater:
MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
FolderCreate = False
Exit Function
End Function
Function FolderExists(ByVal path As String) As Boolean
FolderExists = False
Dim fso As New FileSystemObject
If fso.FolderExists(path) Then FolderExists = True
End Function
Function CleanName(strIn As String) As String
'will clean part # name so it can be made into valid folder name
'may need to add more lines to get rid of other characters
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Global = True
.Pattern = "[,\/\*\.\\""""]+"
CleanName = .Replace(strIn, vbNullString)
End With
End Function
(source: kaboomlabs.com)
As you see above C3 should be cleaned up. I don't have the folder protected or locked. I created the folder yesterday in hopes to get it working.
Code and information here: CreateFolder Sheet and scripts
Try changing your code to
If Not FolderExists(strPath & strCompany) Then
'Company doesn't exist, so first create company folder and then part folder
FolderCreate strPath & strCompany
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strCompany & Application.PathSeparator & strPart) Then
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
End If
End If
EDIT:
replace this bit:
If Not FolderExists(strPath & strCompany) Then
'company doesn't exist, so create full path
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strCompany & Application.PathSeparator & strPart) Then
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
End If
End If
No Problem
The issue is that the way you are creating folders will only allow you to create one at a time. So you need to build the path up, maybe something like:
Function CreatePath(path As String) As Boolean
Dim pPath As String
Dim x as long
Dim arr
arr = Split(path, "\")
For x = LBound(arr) To UBound(arr)
If x = 0 Then
pPath = arr(x)
Else
pPath = pPath & "\" & arr(x)
End If
If Len(Dir(pPath, vbDirectory)) = 0 Then MkDir pPath
Next x
If Len(Dir(pPath, vbDirectory)) > 0 Then CreatePath = True
End Function
Which will create a path of any depth.
Ok, it with an old script I have, added more stuff to the workbook cell wise, but it works the way I need it too.
Here is the code:
Dim baseFolder As String, newFolder As String
lastrow = wsJL.Cells(Rows.Count, "B").End(xlUp).Row
wsJL.Range("S2:U2").Copy wsJL.Range("S3:U" & lastrow)
Range("J3:M" & lastrow).Calculate
Range("S3:U" & lastrow).Calculate
baseFolder = wbBK1.path & Application.PathSeparator & "Photos" & Application.PathSeparator
'folders will be created within this folder - Change to sheet of your like.
If Right(baseFolder, 1) <> Application.PathSeparator Then _
baseFolder = baseFolder & Application.PathSeparator
For Each cell In Range("S3:S" & lastrow) 'CHANGE TO SUIT
'Company folder - column S
newFolder = baseFolder & cell.Value
If Len(Dir(newFolder, vbDirectory)) = 0 Then MkDir newFolder
'Part number subfolder - column T
newFolder = newFolder & Application.PathSeparator & cell.Offset(0, 1).Value
If Len(Dir(newFolder, vbDirectory)) = 0 Then MkDir newFolder
Next
End With
I have in S and T is this:
S
=TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($C2,",","")," "," "),".",""),"/","-"),"""",""),"*",""))
T
=TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($D2,",","")," "," "),".",""),"/","-"),"""",""),"*",""))
This trims the end of all the cells of any blank spaces that we don't see, and cleans up the cells so it's accurate and possible to have a folder created in it.