Subscript out of range in Excel VBA workbook name [duplicate] - excel

I pulled some code from online to open the latest file in a folder, which seems to work well. Later in the code however, I added an additional line to SET that same, recent file which was opened. The Workbook subscipt is out range when trying this and I think it has something to do with the syntax? May need to incorporate additional quotes into the workbook name, any ideas?
The 'path' and 'latestFile' variables seem to be reading in correctly
Dim path$, file$, latestFile$
Dim LatestDate As Date, LMD As Date
Dim D As worksheet, dash As worksheet
'open latest file
path = "R:\Dept\"
If Right(path, 1) <> "\" Then path = path & "\"
file = Dir(path & "*.xls", vbNormal)
If Len(file) = 0 Then
MsgBox "No files were found in the folder", vbExclamation
End If
Do While Len(file) > 0
LMD = FileDateTime(path & file)
If LMD > LatestDate Then
latestFile = file
LatestDate = LMD
End If
file = Dir
Loop
Application.DisplayAlerts = False
Workbooks.Open path & latestFile
Application.DisplayAlerts = True
Set dash = Workbooks("dashboard.xlsm").Worksheets("D data")
Set D = Workbooks(path & latestFile).Worksheets("D Data") 'error here

Just use the name:
Set D = Workbooks(latestFile).Worksheets("D Data")
But cleaner to do this:
Application.DisplayAlerts = False
Set D = Workbooks.Open(path & latestFile).Worksheets("D Data") '<< edit
Application.DisplayAlerts = True

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 newest file from wildcards vba

Good day,
I am trying to open an archived workbook in the "Archive" folder to copy contents of a worksheet to a new workbook with the same sheet name.
There are multiple files in folder and the opened file depends on the customer name. (there will be multiple customers and multiple workbooks with a single customer)
The file names are all structured as PREFIX (FSO or PPG), Ticket Number (111234), Customer Name, Job Type and Short Date, like, "FSO 111234 Co Name Job Type 022822.xlsm"
My issue is that the following code opens the first file in the folder and not the newest file. I require the newest file from the wild carded customer name.
Public Sub Archive_Ticket_Fill()
Dim xpath, xfile, LatestFile As String
Dim InternalWB, wb As Workbook
Dim LatestDate, LMD As Date
Set wb = Nothing
xpath = "C:\Start\Archive\"
If Right(xpath, 1) <> "\" Then xpath = xpath & "\"
xfile = Dir$(xpath & "*" & Worksheets("DM").Range("D10").Value & "*.xlsm", vbNormal)
If Len(xfile) = 0 Then Exit Sub
Do While Len(xfile) > 0
LMD = FileDateTime(xpath & xfile)
If LMD >= LatestDate Then
LatestFile = xfile
LatestDate = LMD
End If
xfile = Dir
Loop
On Error Resume Next
Set wb = Workbooks(LatestFile)
On Error GoTo 0
If wb Is Nothing Then
Set InternalWB = Workbooks.Open(xpath & LatestFile)
'COPY CODE HERE
Else
MsgBox LatestFile & " is already open."
'COPY CODE HERE
End If
End Sub
Any suggestions or help is appreciated. Thank you for your time.

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.

Pull Filename From Latest File

I am using the following code (co-opted from someone here) to access the latest generated files from a folder. I use it to open the file and do various bits (example below). But I was wondering if there is a way to pull the filename from the latest file and paste it into a cell in another workbook?
Sub Macro3()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
Application.DisplayAlerts = False
MyPath = "C:\Users\XXXX\Desktop\folderXXX"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "XYZ-********-123.csv", 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
Range("B2:D97").Copy
ActiveWindow.Close
Windows("New.xlsm").Activate
Range("A2").Select
ActiveSheet.Paste
End Sub
Can it been done with the existing code, is it as simple as adding something to this line Workbooks.Open MyPath & LatestFile instead of .Open?
Appreciate any help or tips even tips to tidy it up in any way. Thanks
You can do something like this:
Sub Macro3()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
Dim wb As WorkBook, wsDest As Worksheet '<<<
Application.DisplayAlerts = False
MyPath = "C:\Users\XXXX\Desktop\folderXXX"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "XYZ-********-123.csv", 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
Set wsDest = ThisWorkbook.WorkSheets("Data") '<< for example
Set wb = Workbooks.Open(MyPath & LatestFile)
wb.Sheets(1).Range("B2:D97").Copy wsDest.Range("A2")
wb.Close False '<< don't save
wsDest.Range("A1").Value = LatestFile '<< record the file name
End Sub

Resources