Rename multiple files by name Excel VBA - excel

I am very new to vba and I need a excel macro that depending on the file name, assigns it another name, for example:
aaa12345.txt -----> hello.txt
bb678.txt -----> bye.txt
there are only two types of names in the folder, aaa*.txt and bb*.txt
Sub rena_me()
if ffile = Dir("C:\test\aaa*.txt") Then NewName = "yellow.txt"
Name "C:\test\" & ffile As "c:\test\" & NewName
End sub
this code is all I have got... works fine, but I don't know how to implement it for both files

Try the following macro...
Option Explicit
Sub rena_me()
Dim myPath As String
Dim myFile As String
Dim newName As String
myPath = "C:\test\"
'check for an aaa file
myFile = Dir(myPath & "aaa*.txt")
If Len(myFile) > 0 Then
Name myPath & myFile As myPath & "hello.txt"
End If
'check for a bb file
myFile = Dir(myPath & "bb*.txt")
If Len(myFile) > 0 Then
Name myPath & myFile As myPath & "bye.txt"
End If
End Sub

Related

VBA from latest file in a folder ("Run-time error 1004")

I used the below code to open the latest file in a folder and Vlookup from it and return the value which is in column I.
I am facing a Run-time error 1004, although everything is correct.
i Set wbname = ActiveWorkbook.Name to catch the open sheet name which I will put the Vlookup formula in and I am choosing the correct range for my formula which is I2, still can't figure out where did I go wrong.
Error Message in the below line:
Range("I2").Formula = _
"=VLOOKUP(A2,[" & MyPath & LatestFile & "]'Sheetname with input data'!A:I,9,False)"
My Code:
Sub PrepareforOutlookMails()
wbname = ActiveWorkbook.Name
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
Dim wb As Workbook
Dim fileLocation As String
Dim fileToOpen As Workbook
MyPath = "C:\1.ER\1.Work\19.Etr\Recon\2022\October"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
'first Excel file from the folder
MyFile = Dir(MyPath & "*.xls", vbNormal)
'If no files exit the sub
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
'Loop through each Excel file in the folder
Do While Len(MyFile) > 0
LMD = FileDateTime(MyPath & MyFile)
If LMD > LatestDate Then
LatestFile = MyFile
LatestDate = LMD
End If
MyFile = Dir
Loop
Workbooks.Open MyPath & LatestFile
Workbooks(wbname).Activate
Range("I2").Formula = _
"=VLOOKUP(A2,[" & MyPath & LatestFile & "]'Sheetname with input data'!A:I,9,False)"
Like I mentioned VLOOKUP works on closed file as well. There is no need to open the file.
Your [ and ] and ' placement is incorrect. Here is an example (Untested)
If you manualy type the formula, it will look like this
=VLOOKUP(D2,'C:\1.ER\1.Work\19.Etr\Recon\2022\October\[Mail Merge (Updated Sample File) (1).xlsx]Sheetname with input data'!A:I,9,0)
Sub Sample()
Dim MyPath As String
Dim LatestFile As String
MyPath = "C:\1.ER\1.Work\19.Etr\Recon\2022\October\"
LatestFile = "Mail Merge (Updated Sample File) (1).xlsx"
Range("I2").Formula = "=VLOOKUP(A2,'" & _
MyPath & _
"[" & _
LatestFile & _
"]Sheetname with input data'!A:I,9,0)"
End Sub
EDIT
This is how your original code can be written. I have commented the code so you should not have any problem understanding it.
Option Explicit
Sub PrepareforOutlookMails()
Dim wbThis As Workbook
Dim wsThis As Worksheet
Dim MyPath As String
Dim MyFile As String
Dim LMD As Date
Dim LatestFile As String
Dim LatestDate As Date
Set wbThis = ThisWorkbook
'~~> Change this to the relevant sheet
'~~> This is where the formula will be written
Set wsThis = wbThis.Sheets("Sheet1")
'MyPath = "C:\1.ER\1.Work\19.Etr\Recon\2022\October"
MyPath = "C:\Users\routs\Desktop"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
'~~> First Excel file from the folder
MyFile = Dir(MyPath & "*.xls*", vbNormal)
'~~> If no files exit the sub
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
'Loop through each Excel file in the folder
Do While Len(MyFile) > 0
LMD = FileDateTime(MyPath & MyFile)
If LMD > LatestDate Then
LatestFile = MyFile
LatestDate = LMD
End If
MyFile = Dir
Loop
wsThis.Range("I2").Formula = "=VLOOKUP('" & wsThis.Name & "'!A2,'" & _
MyPath & _
"[" & _
LatestFile & _
"]Sheetname with input data'!A:I,9,0)"
End Sub
Screenshot

VBA code to automatically import "NEWEST" csv file into specific sheet

I am wanting to write a VBA code to import the newest .csv file from a certain directory into a specific excel sheet. I am currently using a code that works, BUT it opens up in a new workbook and I cannot figure out how to append it to a certain sheet instead. If that makes sense? Also, is there a way to also delete all duplicates within that specific sheet after imported?
The code I am currently using through VBA is below....
Option Explicit
Sub NewestFile()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
MyPath = "C:\Users\Documents\"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xls", vbNormal)
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
Do While Len(MyFile) > 0
LMD = FileDateTime(MyPath & MyFile)
If LMD > LatestDate Then
LatestFile = MyFile
LatestDate = LMD
End If
MyFile = Dir
Loop
Workbooks.Open MyPath & LatestFile
End Sub
The issue is that this code opens up in a new workbook instead of importing into a specific sheet.

Open the latest version of a file in a folder respecting a pattern

I have a folder that during the day can be updated with files named according to these patterns ("D0_yyyymmdd.xlsx") and ("D1_yyyymmdd"). So, for example we can find "D0_20200506" and "D1_20200506".
I am writing a program where depending on the user request ("D0" or "D1") I have to get the information of the latest version available in the folder. I already have a code that works for openning the latest file, but the code does not respect the user request "D0" or "D1". Having said that, if the user request is "D0" I have to get information from the latest version of files that follow the "D0_yyyymmdd.xlsx" pattern.
Can someone help me?
'Force the explicit declaration of variables
Option Explicit
Sub OpenLatestFile()
'Declare the variables
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
Dim closedBook As Object
Dim GetBookName As String
GetBookName = ActiveWorkbook.Name
'Specify the path to the folder
MyPath = "\\testingcode\"
'Make sure that the path ends in a backslash
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
'Get the first Excel file from the folder
MyFile = Dir(MyPath & "*.xlsx", vbNormal)
'If no files were found, exit the sub
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
'Loop through each Excel file in the folder
Do While Len(MyFile) > 0
'Assign the date/time of the current file to a variable
LMD = FileDateTime(MyPath & MyFile)
'If the date/time of the current file is greater than the latest
'recorded date, assign its filename and date/time to variables
If LMD > LatestDate Then
LatestFile = MyFile
LatestDate = LMD
End If
'Get the next Excel file from the folder
MyFile = Dir
Loop
'Open the latest file
Application.ScreenUpdating = False
Workbooks.Open MyPath & LatestFile
Sheets(1).Copy After:=Workbooks(GetBookName).Sheets(Sheets.Count)
Workbooks(LatestFile).Close SaveChanges:=False
Application.ScreenUpdating = True
Choose Either Using Buttons
For CommandButton1 and CommandButton2 change their Caption to D0 and D1. Then use the following in the Sheet Code e.g. Sheet1:
Option Explicit
Private Sub CommandButton1_Click()
OpenLatestFile Me.CommandButton1.Caption
End Sub
Private Sub CommandButton2_Click()
OpenLatestFile Me.CommandButton2.Caption
End Sub
Now make the sub 'argumented' in the following way:
Sub OpenLatestFile(CmdCaption As String)
Change the appropriate line by doing the following:
If the filename starts with D0 or D1 use:
'Get the first Excel file from the folder
MyFile = Dir(MyPath & CmdCaption & "*.xlsx", vbNormal)
If the filename only contains D0 or D1 use:
'Get the first Excel file from the folder
MyFile = Dir(MyPath & "*" & CmdCaption & "*.xlsx", vbNormal)
The sub should stay in a standard module e.g. Module1.

Open Last File save base on creation date, NOT Last modify

I'm new on VBA, currently, I been seen the way to open a workbook base on creation date, I have found several codes but this open last save workbook or last modify file, sometimes last files are not the workbook I need and I will like to replace from last save file to the creation date.
Below its an example of code, I have found.
Sub NewestFile()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
MyPath = "C:\Users\Documents\"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xls", vbNormal)
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
Do While Len(MyFile) > 0
LMD = FileDateTime(MyPath & MyFile)
If LMD > LatestDate Then
LatestFile = MyFile
LatestDate = LMD
End If
MyFile = Dir
Loop
Workbooks.Open MyPath & LatestFile
End Sub

Trying to rename a file in a folder (based on a string within the filename)

Hi there I am trying to create a Sub where I find a file in a folder with the name containing a specific phrase like "test_file" and rename it with a different name/extension. I have the following code that doesn't seem to work: (Also I don't know how to search for a specific string within a filename and execute the renaming according to that)
Sub ReName()
Dim myFile As String
Dim myPath As String
Dim mVal As String
mVal = "_12345678_" 'test string'
myPath = "C:\Users\bf91955\Desktop\testfolder\" 'folder path'
myFile = Dir(pathname & "*test_file*") 'real file name is 2222_test_test_file.xlsx'
myFile = myPath & myFile
NewName = "new_test_file & mVal & .xlsx" 'save it as .xlsx and with the new filename including myVal'
Name myFile As myPath & NewName 'rename
End Sub
Any help would be appreciated!
Have a look at the comments you had a couple of errors
Sub ReName()
Dim myFile As String
Dim myPath As String
Dim mVal As String
mVal = "_12345678_" 'test string'
myPath = "C:\Users\bf91955\Desktop\testfolder\" 'folder path'
'' You weren't referencing MyPath here - guessing copy and paste error
myFile = Dir(myPath & "*test_file*") 'real file name is 2222_test_test_file.xlsx'
myFile = myPath & myFile
'' This was passing the variable as part of the string
newname = "new_test_file" & mVal & ".xlsx" 'save it as .xlsx and with the new filename including myVal'
Name myFile As myPath & newname 'rename
End Sub

Resources