Excel 2010 VBA Check for Part of a file path - excel

Hi I am trying to create a code that checks for part of a file name and then will save the document with a increment of that file name, for example the below is creating a file name then using left to get just the part I want to check if it exists in any form but how do I check if a filename contains that info
TicketNumber = "0"
FileE = 1
UName = Range("C1")
On Error GoTo ErrorDocumentName
With New FileSystemObject
Do While FileE = 1
FileName = "REM" & TicketNumber & " - " & UName & ".xlsm"
Pos = InStr(FileName, "-")
LeftFN = Left(FileName, Pos - 2)
LeftFP = ThisWorkbook.Path & "\" & LeftFN
FileP = ThisWorkbook.Path & "\" & FileName
DisplayName = "REM" & TicketNumber
If .FileExists(LeftFP & WildC) Then
TicketNumber = TicketNumber + 1
ElseIf Not .FileExists(LeftFP & WildC) Then
FileE = 0
End If
Loop
End With
On Error GoTo ErrorRunning
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=FileP, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
ActiveSheet.Name = "Incident"
ActiveWorkbook.Save
Application.DisplayAlerts = True
Exit Sub

Related

VBA: Automatically saving the excel sheet as V-1, V-2 and V-3 depending on if there is a file with that name already in the folder

I am working in VBA. I want to save the excel document with values from my sheet. However, repeats of the same file name can exist. If the same file name is repeated, I would like the VBA to save it as a different version number. For example, if the file name is CAT DOG and there is a second file saved as CAT DOG, I want the VBA to automatically save it as V-2. And if there is already a V-2, to than save if as V-3 and so on. This is the code I have so far. It saves great normally but I am having trouble with getting the version numbers added. I have attached an image of the code so far
''''
path = ""
filename1 = ws.Range("D5").Text &
ws.Range("O3").Text`e`ws.Range("D6").Text
If filename1(path & filename1 & ".xlsm") = False Then
ActiveWorkbook.SaveAs Filename:=(path & filename1 & ".xlsm"),
FileFormat:=xlOpenXMLWorkbookMacroEnabled
Exit Sub
End If
Do While Saved = False
If filename1(path & filename1 & x & ".xlsm") = False Then
ActiveWorkbook.SaveAs Filename:=(path & filename1 & x & ".xlsm"),
FileFormat:=xlOpenXMLWorkbookMacroEnabled
Saved = True
Else
x = x + 1
End If
Loop
MsgBox "New file version saved (version " & x & ")"
Do Not Overwrite Saved Files (Versioning)
Adjust the values in the constants section.
Using the current setup, it will create files with the following names:
CAT DOG.xlsm
CAT DOG (V-2).xlsm
CAT DOG (V-3).xlsm
etc.
in the Test folder on drive C.
The Code
Option Explicit
Sub DoNotOverWrite()
Const dFolderPath As String = "C:\Test\"
Const dBaseName As String = "CAT DOG"
Const dLeft As String = " (V-"
Const dFirstNumber As Long = 2
Const dRight As String = ")"
Const dExtension As String = ".xlsm"
Dim dFilePath As String: dFilePath = dFolderPath & dBaseName & dExtension
Dim dFileName As String: dFileName = Dir(dFilePath)
Dim n As Long: n = dFirstNumber - 1
Do Until Len(dFileName) = 0
n = n + 1
dFilePath = dFolderPath & dBaseName & dLeft & n & dRight & dExtension
dFileName = Dir(dFilePath)
Loop
' If the workbook is the one containing this code, use 'ThisWorkbook'.
ActiveWorkbook.SaveAs dFilePath, xlOpenXMLWorkbookMacroEnabled
If n < dFirstNumber Then
MsgBox "File saved.", vbInformation
Else
MsgBox "New file version saved (version " & n & ")", vbInformation
End If
End Sub

How to save the active workbook in another folder in Excel VBA?

I am trying to automatically save my active workbook into another folder on my computer and if there is already a file with the name of my workbook in that folder, then it should be saved with "_v1"/"_v2" and so on at the end of its name.
I have found this code but it works just for the current folder, where the workbook is saved.
Sub SaveNewVersion_Excel()
Dim FolderPath As String
Dim myPath As String
Dim SaveName As String
Dim SaveExt As String
Dim VersionExt As String
Dim Saved As Boolean
Dim x As Long
TestStr = ""
Saved = False
x = 2
VersionExt = "_v"
On Error GoTo NotSavedYet
myPath = "O:\Operations\Department\Data Bank Coordinator\_PROJECTS_\QC BeadRegion Check\Multi Ref Archiv"
myFileName = Mid(myPath, InStrRev(myPath, "\") + 1, InStrRev(myPath, ".") - InStrRev(myPath, "\") - 1)
FolderPath = Left(myPath, InStrRev(myPath, "\"))
SaveExt = "." & Right(myPath, Len(myPath) - InStrRev(myPath, "."))
On Error GoTo 0
If InStr(1, myFileName, VersionExt) > 1 Then
myArray = Split(myFileName, VersionExt)
SaveName = myArray(0)
Else
SaveName = myFileName
End If
If FileExist(FolderPath & SaveName & SaveExt) = False Then
ActiveWorkbook.saveAs FolderPath & SaveName & SaveExt
Exit Sub
End If
Do While Saved = False
If FileExist(FolderPath & SaveName & VersionExt & x & SaveExt) = False Then
ActiveWorkbook.saveAs FolderPath & SaveName & VersionExt & x & SaveExt
Saved = True
Else
x = x + 1
End If
Loop
Exit Sub
NotSavedYet:
MsgBox "This file has not been initially saved. " & _
"Cannot save a new version!", vbCritical, "Not Saved To Computer"
End Sub
Function FileExist(FilePath As String) As Boolean
Dim TestStr As String
On Error Resume Next
TestStr = Dir(FilePath)
On Error GoTo 0
If TestStr = "" Then
FileExist = False
Else
FileExist = True
End If
End Function
It works for the current folder but when I change the folder path it doesn't work.
I would very much appreciate it if you could help me.
Thanks!
Sergiu
I've assumed the new folder is "D:_PROJECTS_\Multi Ref Archiv" and that if the existing file is zzzz_v07.xlsm then you want this saved as zzzz_v08.xlsm even when there are no previous versions in the folder. I added the leading zero so they sort nicely!
Sub SaveNewVersion_Excel2()
Const FOLDER = "D:\_PROJECTS_\Multi Ref Archiv" ' new location
Const MAX_FILES = 99
Dim oFSO As Object, oFolder As Object, bOK As Boolean, res As Variant
Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim sFilename As String, sFilename_v As String
' filename only
sFilename = ThisWorkbook.Name
' check folder exists
If Not oFSO.folderexists(FOLDER) Then
bOK = MsgBox(FOLDER & " does not exist. Do you want to create ?", vbYesNo, "Confirm")
If bOK Then
oFSO.createFolder FOLDER
MsgBox "OK created " & FOLDER, vbInformation
Else
Exit Sub
End If
End If
' get next name
sFilename_v = Next_v(sFilename)
' check if exists
Dim i As Integer: i = 1
Do While oFSO.fileexists(FOLDER & "\" & sFilename_v) = True And i <= MAX_FILES
i = i + 1
sFilename_v = Next_v(sFilename_v)
Loop
' check loop ok
If i > MAX_FILES Then
MsgBox "More than " & MAX_FILES & " files already exist", vbExclamation
Exit Sub
End If
sFilename_v = FOLDER & "\" & sFilename_v
' confirm save
res = MsgBox("Do you want to save to " & sFilename_v, vbYesNo, "Confirm")
If res = vbYes Then
ActiveWorkbook.SaveAs sFilename_v
MsgBox "Done", vbInformation
End If
End Sub
Function Next_v(s As String)
Const ver = "_v"
Dim i As Integer, j As Integer, ext As String, rev As Integer
i = InStrRev(s, ".")
j = InStrRev(s, ver)
ext = Mid(s, i)
' increment existing _v if exists
If j > 0 Then
rev = Mid(s, j + 2, i - j - 2)
s = Left(s, j - 1)
Else
rev = 0
s = Left(s, i - 1)
End If
Next_v = s & ver & Format(rev + 1, "00") & ext
End Function
You can move all of the logic out to a separate function, then you only need to call that to get the "correct" name to save as.
'Pass in the full path and filename
' Append "_Vx" while the passed filename is found in the folder
' Returns empty string if the path is not valid
Function NextFileName(fPath As String)
Const V As String = "_V"
Dim fso, i, p, base, ext
Set fso = CreateObject("scripting.filesystemobject")
'valid parent folder?
If fso.folderexists(fso.GetParentFolderName(fPath)) Then
p = fPath
ext = fso.getextensionname(p)
base = Left(p, Len(p) - (1 + Len(ext))) 'base name without extension
i = 1
Do While fso.fileexists(p)
i = i + 1
p = base & (V & i) & "." & ext
Loop
End If
NextFileName = p
End Function

Renaming a existing closed file but "Name" method showing error

I am trying to save a file but before that I am checking if the same name file already exists in the same folder, if it's there, I rename the old existing file (add a timestamp to it's name) and move it to a different folder location. For renaming I am using "Name" method but it's showing error.
I have already tested that a file with same name already exists.The timestamp to be added is also coming up. Below is the code.
Dim Test As String
On Error Resume Next
Test = Dir(ThisWorkbook.Sheets("Sheet1").Range("B5").Text)
On Error GoTo 0
If Test = "" Then
fileexist = False
Else
fileexist = True
Timestamp = CStr(FileDateTime(ThisWorkbook.Sheets("Sheet1").Range("B5").Text))
Newname = Left((ThisWorkbook.Sheets("Sheet1").Range("B5").Text), Len((ThisWorkbook.Sheets("Sheet1").Range("B5").Text)) - 5) & Timestamp & ".xlsx"
Name (ThisWorkbook.Sheets("Sheet1").Range("B5").Text) As Newname
'*** Just this last above statment is giving error
End if
The file already exists so why is the Name method giving error? Thanks in advance for any help.
Maybe give this a try :
Sub tryme()
Dim test As String
On Error Resume Next
test = Dir(ThisWorkbook.Path & "\" & ThisWorkbook.Sheets("Sheet1").Range("B5").Text)
On Error GoTo 0
If test = "" Then
fileexist = False
Else
fileexist = True
Timestamp = CStr(FileDateTime(ThisWorkbook.Path & "\" & ThisWorkbook.Sheets("Sheet1").Range("B5").Text))
newname = Left((ThisWorkbook.Sheets("Sheet1").Range("B5").Text), Len((ThisWorkbook.Sheets("Sheet1").Range("B5").Text)) - 5) & Format(Timestamp, "ddmmmyyyy") & ".xlsm"
ThisWorkbook.SaveAs FileName:=ThisWorkbook.Path & "\" & newname
End If
End Sub
If the path is in B5 then just do as follow :
Dim Test As String
On Error Resume Next
Test = Dir(ThisWorkbook.Sheets("Sheet1").Range("B5").Text)
On Error GoTo 0
If Test = "" Then
fileexist = False
Else
fileexist = True
Timestamp = CStr(FileDateTime(ThisWorkbook.Sheets("Sheet1").Range("B5").Text))
Newname = Left((ThisWorkbook.Sheets("Sheet1").Range("B5").Text), Len((ThisWorkbook.Sheets("Sheet1").Range("B5").Text)) - 5) & Format(Timestamp, "ddmmmyyyy") & ".xlsx"
'Name (ThisWorkbook.Sheets("Sheet1").Range("B5").Text) As Newname
ThisWorkbook.SaveAs FileName:=ThisWorkbook.Path & "\" & Newname
End if

Determine if file exists

I want to open workbook up to variable in the archive list.
If I don't have the file in the archive, I want it to show a message box, but it did not work.
strVariable = Left(PictureNo, 4)
d = "Teknik Resim Arsiv Listesi_" & strVariable & ".xls"
Dim Ret
Ret = Workbooks.Open(ThisWorkbook.Path & Application.PathSeparator & d)
If Ret = False Then
MsgBox "Not Found"
End If
Check for the existence of the file before attempting to open it:
strVariable = Left(PictureNo, 4)
d = "Teknik Resim Arsiv Listesi_" & strVariable & ".xls"
If Dir(ThisWorkbook.Path & Application.PathSeparator & d) = "" Then
MsgBox "Not Found"
Else
Dim wb As Workbook
Set wb = Workbooks.Open(ThisWorkbook.Path & Application.PathSeparator & d)
End If

Looping through Mail items but skipping an email

I am trying to loop through all emails in a mailbox and extract the attachment from each. The loop works as expected if I don't have the delete included. With the delete included it works for the first email and on the "next" statement exits the for loop, skipping the remaining email. I could separate out the delete to a new loop but that seems inefficient.
For Each itm In Inbox.Items
For Each objAtt In itm.Attachments
sEmailDate = Format(itm.ReceivedTime, "dd/mm/yyyy")
sDataDate = Format(DateAdd("d", -1, CDate(sEmailDate)), "dd/mm/yyyy")
sFileName = objAtt.Filename
sSubject = itm.Subject
'Check if the report was sent today
If sEmailDate = sTodayDate And sFileName = "Report.csv" Then
bToday = True
End If
'Look for Report file
If sFileName = "Report.csv" Then
'Save it to the save folder, as the DisplayName. This will overwrite previously saved copies of this file
objAtt.SaveAsFile saveFolder & "\" & "report" & sSubject & "_" & Format(sDataDate, "yyyymmdd") & ".csv"
If Err.Number = 0 Then
itm.Delete 'without this istwill loop correctly
iReportCount = iReportCount + 1
Else
GoTo ExitLoop
End If
End If
Next objAtt
Next itm
Use the For loop instead of For Each one:
Dim items as Outlook.Items
Set items = Inbox.Items
For i = items.Count to 1 Step -1
For Each objAtt In itm.Attachments
sEmailDate = Format(itm.ReceivedTime, "dd/mm/yyyy")
sDataDate = Format(DateAdd("d", -1, CDate(sEmailDate)), "dd/mm/yyyy")
sFileName = objAtt.Filename
sSubject = itm.Subject
'Check if the report was sent today
If sEmailDate = sTodayDate And sFileName = "Report.csv" Then
bToday = True
End If
'Look for Report file
If sFileName = "Report.csv" Then
'Save it to the save folder, as the DisplayName. This will overwrite previously saved copies of this file
objAtt.SaveAsFile saveFolder & "\" & "report" & sSubject & "_" & Format(sDataDate, "yyyymmdd") & ".csv"
If Err.Number = 0 Then
itm.Delete
iReportCount = iReportCount + 1
Else
GoTo ExitLoop
End If
End If
Next
Next

Resources