duplicate file checking when exporting - excel

can someone tell me what im doing wrong, I am trying to export a file and if the file exists to add duplicate onto the end of it, I cant seem to get it to work
Dim FilePath As String
Dim FileName As String
Dim MyDate As String
Dim megalist As String
Dim FileCopy As String
Dim copy As String
copy = " Duplicate"
FilePath = "Q:\RADIOLOGY\ADMINISTRATION\DATA\CT DISTRIBUTION\PAY ROLL\"
MyDate = Format(Date, "MM-DD-YYYY")
megalist = " Megalist"
FileName = FilePath & MyDate & megalist
FileCopy = FilePath & MyDate & megalist & copy
If Dir(FilePath) <> MyDate & Report Then
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, FileName:=FileName
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=FileCopy
End If
End Sub

See below answer to generate your FileName.
https://stackoverflow.com/a/31706252/1684486
and then simply use ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, FileName:=FileName
EDiT
in your case:
FilePath = "Q:\RADIOLOGY\ADMINISTRATION\DATA\CT DISTRIBUTION\PAY ROLL\"
MyDate = Format(Date, "MM-DD-YYYY")
megalist = " Megalist"
FileName = GetNextAvailableName(FilePath & MyDate & megalist)
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, FileName:=FileName
of course you need to copy the GetNextAvailableName function from that answer to a public module in your project.

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

Saving a Excel sheet

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?

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

How to open a workbook named after a cell in the worksheet?

I am trying to convert one txt file onto an excel one. I have the code for this. the problem is that my txt file will have a different name every day based on the date. therefore I have a cell in my workbook following the same name which I want to use to refer to the correct workbook.
When I press F5, I get a constant expression required error on the name of the file I call (line 3: " & varCellvalue & ".xls")
the name of the file I want to open is in C1.
Do you have any idea how to work around this error?
My code:
Sub Convert()
DimvarCellvalue As Long
varCellvalue = Range("C1").Value
Const txtFldrPath As String = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & varCellvalue & ".xls"
Const xlsFldrPath As String = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Payments Holidays"
Dim CurrentFile As String: CurrentFile = Dir(txtFldrPath & "\" & "*.txt")
Dim strLine() As String
Dim LineIndex As Long
Application.ScreenUpdating = False
Application.DisplayAlerts = False
While CurrentFile <> vbNullString
LineIndex = 0
Close #1
Open txtFldrPath & "\" & CurrentFile For Input As #1
While Not EOF(1)
LineIndex = LineIndex + 1
ReDim Preserve strLine(1 To LineIndex)
Line Input #1, strLine(LineIndex)
Wend
Close #1
With ActiveSheet.Range("A1").Resize(LineIndex, 1)
.Value = WorksheetFunction.Transpose(strLine)
.TextToColumns Other:=True, OtherChar:="|"
End With
ActiveSheet.UsedRange.EntireColumn.AutoFit
ActiveSheet.Copy
ActiveWorkbook.SaveAs xlsFldrPath & "\" & Replace(CurrentFile, ".txt", ".xlsx"), xlOpenXMLWorkbook
ActiveWorkbook.Close False
ActiveSheet.UsedRange.ClearContents
CurrentFile = Dir
Wend
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
In this line
Const txtFldrPath As String = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & varCellvalue & ".xls"
You have declared the txtFldrPath as constant, so you can't use a variable with it varCellvalue
Declare the varCellvalue as variable Dim txtFldrPath As String
then assign the value as you wish
Dim txtFldrPath As String
txtFldrPath = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & varCellvalue & ".xls"

How to fix "Bad File Name or Number" error when saving an Excel file via macro?

I need to save my excel file using a macro and I am making use of an old macro I made a while ago - which worked just fine. But now, I am getting an error which I don't seem to understand all to well.
Code:
Option Explicit
Sub SaveFile()
Dim strDir As String, saveDate As String, userMachine As String, Filename As String, yearDate As String, monthDate As String, filePath As String
Dim ws1 As Workbook
Set ws1 = Workbooks("Template.xlsm")
Application.DisplayAlerts = False
saveDate = "01/02/2019"
yearDate = Year(saveDate)
monthDate = Format(saveDate, "MMMM")
saveDate = Format(saveDate, "dd-mm-yyyy")
userMachine = "User - 12345"
strDir = "C:\user12345\desktop\Final Results\" & yearDate & "\" & monthDate & "\" & Format(saveDate, "dd-mm-yyyy") & "\"
filePath = ""
Filename = userMachine & " - " & saveDate & ".xlsx"
filePath = Dir(strDir & Filename)
If Dir(strDir, vbDirectory) = "" Then
MkDir strDir
If filePath = "" Then
ws1.SaveAs Filename:=filePath, FileFormat:=51, CreateBackup:=False
Else
MsgBox filePath & " Execution File Exists"
End If
Else
If filePath = "" Then
ws1.SaveAs Filename:=filePath, FileFormat:=51, CreateBackup:=False
Else
MsgBox filePath & " Execution File Exists"
End If
End If
End Sub
The error is on this line filePath = Dir(strDir & Filename) and the error is:
Bad File Name or Number
As far as I can see, my name for the file meets the requirements to save it so I am at a total loss here.
The original code I had was this:
strDir = "C:\username\desktop\" & Format(DateAdd("d", -1, Date), "dd_mm_YY") & "\"
FilePath = Dir(strDir & "myFile.xlsx")
Bad File Name or Number means that the string you are using to save the file is not valid.
You could replace the hardcoded string to your desktop with a relative reference from a function, such as:
Function getDeskTopPath() As String
'Get Desktop path as string
'Command can be exchanged for other information... see list below
'AllUsersDesktop
'AllUsersStartMenu
'AllUsersPrograms
'AllUsersStartup
'Desktop
'Favorites
'Fonts
'MyDocuments
'NetHood
'PrintHood
'Programs
'Recent
'SendTo
'StartMenu
'Startup
'Templates
Dim oShell As Object
Set oShell = CreateObject("Wscript.Shell")
getDeskTopPath = oShell.SpecialFolders("Desktop")
Set oShell = Nothing
End Function

Resources