I am trying to open a file which will be updated periodically. The current name is "GDE Portfolio Characteristics 12.31.2021" and the idea is to instruct the code to open it, no matter the date (i.e. the last 10 characters). I should only have one file in the folder with such a partial name.
The code I use is the following:
Workbooks.Open Filename:=ThisWorkbook.Path & "\Parametric GDE Portfolio Characteristics*.xlsx"
When running it, it seems it does not find the file. It works if I instead use the entire name of the file.
Newbie problem, but scratching my head in frustration!
Many thanks
There is no way to use a wildcard in the Open-statement. However, you can use the
Dir-command to get the real file name as it allows wildcards:
Dim fileName As String
fileName = Dir(ThisWorkbook.Path & "\Parametric GDE Portfolio Characteristics*.xlsx")
If fileName <> "" Then
Workbooks.Open Filename:=ThisWorkbook.Path & "\" & fileName
End If
Here is a more generic approach:
Sub OpenFiles()
Dim Files As Collection
Set Files = ListFiles(ThisWorkbook.Path, "Parametric GDE Portfolio Characteristics*.xlsx")
Dim Filename As Variant
For Each Filename In Files
Workbooks.Open Filename:=Filename
Next
End Sub
Function ListFiles(FolderName As String, SearchString As String) As Collection
Set ListFiles = New Collection
Dim Filename As String
Filename = Dir(FolderName & "\" & SearchString)
If Len(Filename) = 0 Then Exit Function
Do While Filename <> ""
ListFiles.Add Filename
Filename = Dir()
Loop
End Function
Related
I have a file that is placed in a folder, but the date is unknown to me, is there anyway I can pick it up regardless of the date?
FilePath = "\\0_Received\Business_Level_Report_yyyymmdd.xlsx"
The file name will be for example Business_Level_Report_20200729
The date will be unknown but it is the only file with Business Level Report as its prefix.
Can anyone help with this?
Maybe try this solution here: VBA partial file name
You can likely modify this just a bit to get what you're looking for.
For example, in your case you might try this:
myPath = "\\0_Received\"
fname = Dir(myPath & "Business_Level_Report*")
For example, this code opens the workbook named Business_Level_Report_blah_blah_blah without having to specify blah_blah_blah:
Here's the code if you want to run it, too:
Private Sub whatever()
Dim fname As Variant
Dim myPath As String
myPath = "C:\Users\beckj\"
fname = Dir(myPath & "Business_Level_Report*")
If fname <> "" Then
Workbooks.Open (myPath & fname)
MsgBox "File is open."
Else
MsgBox "ERROR."
End If
End Sub
For taday:
FilePath = "\\0_Received\Business_Level_Report_" & Format(Date, "yyyymmdd") & ".xlsx"
for "07/29/2020"
Dim D as Date
D = cDate("07/29/2020")
FilePath = "\\0_Received\Business_Level_Report_" & Format(D, "yyyymmdd") & ".xlsx"
Or if you do not care about a specific date, you must iterate between the folder workbooks and choose the appropriate one in this way:
If fileName like "*Business_Level_Report########.xlsx" then
FilePath = fileName
End If
I have looked at quite a lot of similar questions, but none of them seem to work for my specific issue.
I have a macro that saves my file with a new name if it encounters a file with the same name.
What keeps happening is that it saves the original file to the correct folder, but then when it encounters the file name the next time I save it, the instanced file gets saved to the same folder as the template rather than the folder that they should go to.
In the example below, my template file is saved in the "M:\Excel\" directory.
It saves the first "TEST" file into the "M:\Excel\SavedVersions\" directory since the file name doesn't exist yet.
Then when I run the macro again to have it automatically save an instanced version (ie - "TESTrev1"), it keeps saving the instanced versions to the "M:\Excel\" directory instead of saving it to the "SavedVersions" subfolder.
Not sure what needs to be changed or done differently to get the instanced versions to save to the correct folder.
Any help would be greatly appreciated!
Thanks in advance! :)
Sub TEST()
ActiveWorkbook.Save
ActiveWorkbook.SaveAs Filename:= _
GetNextAvailableName("M:\Excel\SavedVersions\TEST.xlsm")
End Sub
Function GetNextAvailableName(ByVal strPath As String) As String
With CreateObject("Scripting.FileSystemObject")
Dim strFolder As String, strBaseName As String, strExt As String, i As Long
strFolder = .GetParentFolderName("M:\Excel\SavedVersions\")
strBaseName = .GetBaseName("TEST")
strExt = .GetExtensionName(".xlsm")
Do While .FileExists(strPath)
i = i + 1
strPath = .BuildPath(strFolder, strBaseName & "rev" & i & "." & strExt)
Loop
End With
GetNextAvailableName = strPath
End Function
Your code was unnecessarily complex.
Try this simpler version.
Sub TEST()
ActiveWorkbook.Save
ActiveWorkbook.SaveAs fileName:= _
GetNextAvailableName("M:\Excel\SavedVersions\TEST.xlsm")
End Sub
Function GetNextAvailableName(ByVal strPath As String) As String
Dim i as Interger: i = 0
Do Until Len(Dir(strPath)) = 0
i = i + 1
strPath = "M:\Excel\SavedVersions\TESTrev" & i & ".xlsm"
Loop
GetNextAvailableName = strPath
End Function
Keep your code simple. If your path is constant then might as well define a variable for it so that it can be used whenever and whereever you want. This way if there is any change in the path, you have to make the change at only one place.
While saving the file, also specify the FileFormat parameter to avoid problems. You might want to read more about it HERE
Is this what you are trying?
Option Explicit
Const sPath As String = "M:\Excel\SavedVersions\"
Sub Sample()
Dim flName As String
flName = sPath & GetNextAvailableName()
ActiveWorkbook.Save
ActiveWorkbook.SaveAs Filename:=flName, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
Function GetNextAvailableName() As String
Dim i As Integer: i = 1
Dim newFile As String
newFile = "TestRev" & i & ".xlsm"
Do Until Dir(sPath & newFile) = ""
i = i + 1
newFile = "TestRev" & i & ".xlsm"
Loop
GetNextAvailableName = newFile
End Function
Since I am very new to the excel macro I am trying to develop a code which is able to open the PDF file.But There are some PDF files in my system which are generated by another system therefore those files names change day by day and some figures are included too.
As an example,"Process Report 151120183569844" like this.These figures change everyday.I tried it with adding WILDCARD option but it doesn't work.How do I open this PDF with only a part of the file name?
Sub Open_PDF()
Dim pdfPath As String
pdfPath ="D:\Reports\Process Report*" & ".pdf" 'I used wildcard instead "Process Report 151120183569844"'
Call OpenAnyFile(pdfPath)
End Sub
Function openAnyFile(strPath As String)
Set objShell = CreateObject("Shell.Application")
objShell.Open(strPath)
End Function
As pointed out in another answer, the Dir function with a wildcard should do the trick.
Here's an example using the original openAnyFile function.
Sub Open_PDF()
Dim filePath As String, fileName As String
filePath = "D:\Reports\"
fileName = Dir(filePath & "Process Report*.pdf")
If fileName <> "" Then
openAnyFile filePath & fileName
End If
End Sub
Function openAnyFile(strPath As String)
Dim objShell As Object
Set objShell = CreateObject("Shell.Application")
objShell.Open (strPath)
End Function
You cannot open a file using a wildcard - it's just common sense, what if more than one file was matching your criteria - which one would you want to program to open? You have to specify the exact file name to open it.
if there is just one file in the target directory, you can use something like the following code to open it, regardless of its name:
sFound = Dir(ActiveWorkbook.Path & "\Process Report*.xlsm")
If sFound <> "" Then
Workbooks.Open filename:= ActiveWorkbook.Path & "\" & sFound
End If
I randomly create a new folder on my desktop, in this folder I have one template file with .xlsm extension, which contains my VBA code. Meanwhile I have several csv files saved in the same folder with my raw data.
The purpose is looping through all those csv files one by one, open it, and copy some data and paste to my template file(I know how to do this part) from it and close it after all operations are done.
Currently I meet a problem about how to loop through my folder and open those csv one by one. I didn't set a specific folder name, since I want to share it with other people to use,therefore I use Application.ActiveWorkbook.Path to get the path for my current folder.
Here is my code:
Option Explicit
Sub Range_End_Method()
Dim Dir As String
Dim i As String
Application.ScreenUpdating = False
Dir = Application.ActiveWorkbook.Path & "\"
For Each i In Dir.Files
Debug.Print i.Name
If (i.Name Like "*.csv") Then
Workbooks.Open (i.Path)
End If
Next
End Sub
I'm guessing you want to use the Dir function. To use that, make a call to it, specifying folder and file type in the first call, then call it empty until it returns an empty string. Like this:
Folder = Dir(Application.ActiveWorkbook.Path & "\*.csv")
Do While Folder <> ""
Debug.Print Folder
Workbooks.Open Folder
Folder = Dir()
Loop
You can use this function and macro.
Juste replace MsgBox (myFile + "OK") by the action you want to execute.
FUNCTION
Function ClasseurOuvert(NomFich)
On Error Resume Next
Workbooks(NomFich).Activate
If Err <> 0 Then Workbooks.Open FileName:=NomFich
On Error GoTo 0
End Function
MACRO
Sub LoopFiles()
Dim myPath As String, myFile As String
myPath = Application.ActiveWorkbook.Path & "\"
myFile = Dir(myPath & "\*.*")
Do While myFile <> "" And myFile Like "*.csv"
Call ClasseurOuvert(myPath & "\" & myFile)
With Workbooks(myFile)
MsgBox (myFile + "OK")
End With
Workbooks(myFile).Save
Workbooks(myFile).Close
myFile = Dir()
Loop
End Sub
I download reports on a daily/weekly basis but when downloading the system auto generates the file name with a date at the end although the basic file name is the same. ie ANAPOS - 20141001. I'm using a simple open command (Workbooks.OpenText Filename:="C:\Users\903270\Documents\Excel\ANAPOS.txt") to do some other stuff but before doing so I need to rename the file to ANAPOS.txt before I can run it.
Is there any code that will allow my macro to search for ANAPOS with out all the other info at the end?
Any help appreciated.
Set filePath to where you want to search
Sub getANAPOS()
Dim Filter As String, filePath As String
filePath = "C:\Data\VBA\SO\"
Filter = "ANAPOS files (*.txt), filepath & ANAPOS*.txt"
ANAPOSSelectedFile = Application.GetOpenFilename(Filter)
End Sub
EDIT FOLLOWING CLARIFICATION BY OP
Sticking with the same theme, this should give you some scope to work with. It essentially 'automatically' renames the selected file in situ, unless it already exists. Acknowledgements to #Gary's Student for his neat ideas to parse the GetOpenFileName result, here.
Sub renameANAPOS()
Dim Filter As String, filePath As String, newName As String
'filter txt file names containing 'ANAPOS'
Filter = "ANAPOS files (*.txt), filepath & ANAPOS*.txt"
'the 'rename' name
newfName = "ANAPOS"
'navigate to original ANAPOS file and location details
ANAPOSSelectedFile = Application.GetOpenFilename(Filter)
'parse selected file details
fullArr = Split(ANAPOSSelectedFile, "\")
detArr = Split(fullArr(UBound(fullArr)), ".")
fullArr(UBound(fullArr)) = ""
fPath = Join(fullArr, "\")
fName = detArr(0)
fExt = detArr(1)
'rename file in not already exixts
If Len(Dir(fPath & newfName & "." & fExt)) > 0 Then
MsgBox newfName & "." & fExt & " already exists in this folder."
Exit Sub
Else
Name ANAPOSSelectedFile As fPath & newfName & "." & fExt
End If
End Sub