Using a wildcard to open an excel workbook - excel

I want to use a wildcard to open a workbook stored in the same folder as my macro workbook. In the folder is a file named 302113-401yr-r01.xlsm. Here is my code:
Workbooks.Open filename:=ActiveWorkbook.Path & "\302113*.xlsm"
However, it tells me that there is no such file. Any advice?

We cannot open a file using a wildcard - imagine the chaos if we could!
You'll need to use Dir(ActiveWorkbook.Path & "\302113*.xlsm") to loop through the files that this returns. If there will only be one then just use this function once:
Dim sFound As String
sFound = Dir(ActiveWorkbook.Path & "\302113*.xlsm") 'the first one found
If sFound <> "" Then
Workbooks.Open filename:= ActiveWorkbook.Path & "\" & sFound
End If
Dir Function :tech on the net

From my experience this works if you have the wildcard/asterix as the last symbol in the string and if there is only one file. Try doing:
Workbooks.Open filename:=ActiveWorkbook.Path & "\302113*"
For example I am using:
Workbooks.Open Filename:="X:\business\2014\Easy*"
and it works.

You can open files using the wildcard, but only with UNC paths for some reason.
For example :
Set xlFile = xlObj.WorkBooks.Open("\\yourServerHere\dataAutomation\*.xlsx")

I'm not that experienced yet with Excel but the following works well for me for using wildcards in filenames to open files. This example requires all files to be in the same directory/folder. Yes, it is pretty simplistic.
Sub using_wildcards_to_open_files_in_excel_vba()
Dim mypath As String
Dim sFilename As String
'Suppose you have three files in a folder
' Named blank.xlsx,, ex1_939_account.xlsx, and ex1_opt 5.xlsx
'Manually open the blank.xlsx file
'The following code lines will open the second two files before closing the previously opened file.
ActiveWorkbook.Activate
mypath = ActiveWorkbook.Path
'opening xlsx file with name containing "939" and closing current file
mypath = mypath & "\*939*.xlsx"
'MsgBox mypath 'Checking
sFilename = Dir(mypath)
'MsgBox sFilename 'Checking
ActiveWorkbook.Close savechanges:=False
Workbooks.Open Filename:=sFilename
ActiveWorkbook.Activate
mypath = ActiveWorkbook.Path
'opening xlsx file with name ending in "opt 5" and closing current file
mypath = mypath & "\*opt 5.xlsx"
'MsgBox mypath 'Checking
sFilename = Dir(mypath)
'MsgBox sFilename 'Checking
ActiveWorkbook.Close savechanges:=False
Workbooks.Open Filename:=sFilename
End Sub

Related

VBA opening a file with partial name

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

VBA to open Excel Workbook if file exists, and open a different if it does not

I have spent my whole morning on this and cannot get it working properly. A simple Excel userform was created asking for a filename. If the file exists in the directory I want it to open. If it does not exist I want a "template" file opened instead. I have the does not exist working properly, however cannot get the "does exist" part working. Please help.
Private Sub CmdEnter_Click()
Dim Path As String
Dim File As String
Path = Range("Search!B1")
File = TxtOrder.Value
'If File exists then open.
If Dir(Path & File & ".xlsm") = Path & File & ".xlsm" Then
Workbooks.Open FileName:=Path & File & ".xlsm"
'If File does not exist then open.
ElseIf Dir(Path & File & ".xlsm") = Error Then
Workbooks.Open FileName:=Path & "QCSFormTrial.xlsm"
End If
'Close Dialog and Close Workbook
Workbooks("QCSLaunch.XLSM").Close SaveChanges:=False
End Sub
Please, try this way:
Private Sub CmdEnter_Click()
Dim Path As String, File As String, wb As Workbook
Path = Range("Search!B1")
File = TxtOrder.value
'If File exists then open.
If dir(Path & File & ".xlsm") <> "" Then
Set wb = Workbooks.Open(Path & File & ".xlsm")
Else 'else, open the other one:
Set wb = Workbooks.Open(Path & "QCSFormTrial.xlsm")
End If
Stop 'check if the workbook has been open and press F5 to let code finishing
wb.Close SaveChanges:=False
End Sub
The issue is that Dir(Path & File & ".xlsm") = Path & File & ".xlsm" is basically saying does the folder path I named equal the folder path I named. The path isn't actually directed at the actual folder in way that will open it.
Try this: https://exceloffthegrid.com/vba-code-loop-files-folder-sub-folders/
Sub LoopAllFilesInAFolder()
'Loop through all files in a folder
Dim fileName As Variant
fileName = Dir("C:\Users\marks\Documents\")
While fileName <> ""
'Insert the actions to be performed on each file
'This example will print the file name to the immediate window
Debug.Print fileName
'Set the fileName to the next file
fileName = Dir
Wend
End Sub
Or, you can remove the If Then and directly open the file. If the file exists, it will open, if not, it will error. You can use error handling then continue.

How to open files contained in a folder in current file path

I want to open a file (file) that is stored in a folder (Source) which is in the same directory as the current workbook. I get a runtime error 1004 indicating that it the file can't be located. What am I doing worng?
Set x = Workbooks.Open(ThisWorkbook.Path & "\Source\file*.xlsx")
Since you want the wildcard to stay, you need to loop through the files in the folder. Something like this may be of interest to you:
Sub FileOpen()
Dim sPath As String
Dim sFile As String
Dim wb As Workbook
sPath = ThisWorkbook.Path & "\Source\"
sFile = Dir(sPath & "file*.xlsx")
' Loops while there is a next file found in the specified directory
' When there is no next file the Dir() returns an empty string ""
Do While sFile <> ""
' Prints the full path of the found file
Debug.Print sPath & sFile
' Opens the currently found file
Set wb = Workbooks.Open(sPath & sFile)
' Place your code here
' Place your code here
' Place your code here
' Close the current workbook and move on to the next
wb.Close
' This line calls the Dir() function again to get the next file
sFile = Dir()
Loop
End Sub
Good luck!
Replace the wildcard with actual filename.
Set x = Workbooks.Open(ThisWorkbook.Path & "\Source\file.xlsx"
I changed the file*.xlsx to file. xlsx...hope your code works.
thanks.

How to loop and open all csv files in my current folder in VBA

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

Bulk rename worksheets to workbook (file) names in specfic folder

I have 90 Excel sheets in a folder: each Excel file has a unique name (company number) and contains only one worksheet. However the sheet name is generically named to 'Sheet1' in all files. Is there a VBA code that can rename all these sheets in this folder to their respective file name, minus the '.xlsx'?
Basically I want to combine all sheets to one file (I already have that VBA script). However before I can proceed with that, I have to rename all excel sheet names to their unique identifier (which is the file name).
I already looked online, but didn't see this script yet or saw this script for similar other purposes. Thanks in advance!
I found a solution online, credits to user VoG on https://www.mrexcel.com/forum/excel-questions/660913-vba-code-bulk-rename-first-worksheet-dependent-workbook-name.html
This is the solution. Change MyFolder = "C:\example" to respective folder
Sub RenSheets()
Dim MyFolder As String
Dim MyFile As String
Dim wbname As String
MyFolder = "C:\example"
MyFile = Dir(MyFolder & "\*.xls")
Application.ScreenUpdating = False
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
With ActiveWorkbook
wbname = Left(.Name, InStr(.Name, ".") - 1)
.Sheets(1).Name = wbname
.Close savechanges:=True
End With
MyFile = Dir
Loop
Application.ScreenUpdating = True
End Sub

Resources