Reputation: 21
I found the code to open a file from a path (referring to a cell), as well as how to open a file when the complete file name is unknown, however, I'm unable to do both. Is this possible?
Open File From Path:
Dim google_ads_report As Workbook
Dim FromPath As String
' Get path from cell C14 on Report tab
FromPath = Workbooks("Monthly Report - Master.xlsm").Sheets("Macros").Range("C14")
' Make sure there is a backslash at the end of the from path
If Right(FromPath, 1) <> "\" Then FromPath = FromPath & "\"
'Set wkb = ThisWorkbook
Set google_ads_report = Workbooks.Open(FromPath & "hi.xlsx")
Open File with partial Name (because it changes every month):
GA_Transactions = VBA.FileSystem.Dir("C:\Users\tom\Desktop\Analytics Google Ads Revenue - Monthly*.xlsx")
Workbooks.Open "C:\Users\tom\Desktop\" & GA_Transactions
Weirdly, the partial file open code needs the directory both times which after coming across this problem and thinking about it, is strange, right?
I'm assuming there's a way to do it but I can't seem to do it/find it.
Thanks!
Upvotes: 0
Views: 171
Reputation: 2395
The only thing I can think of is looping through the specified folder, and checking if the file name has the required month text. See below code (not tested, but should point you in the right direction).
Option Explicit
Sub Open_File()
Dim fs As Object, sf As Object, file As Variant
Dim sFileName As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set sf = fs.GetFolder("C:\Users\tom\Desktop\")
sFileName = "Analytics Google Ads Revenue - Monthly"
For Each file In sf.Files
If InStr(file.Name, sFileName) > 0 Then
'file found - now execute open method
Exit For
End If
Next file
End Sub
Upvotes: 1