File open inconsistency - excel

I'm using code to open all the files in a folder that start with a particular prefix:
folder = "C:\Users\xxx\Documents\Exception Reports\"
pref = "blah blah prefix"
file = pref & "*.xls"
exPath = folder & file
filename = Dir(exPath)
Do While filename <> ""
Workbooks.Open (filename)
...
Workbooks(filename).Close SaveChanges:=False
filename = Dir()
Loop
The first time I run the code after opening the macro, I get "Sorry we couldn't find -filename-. Is it possible it was moved, renamed, or deleted?" But the -filename- it prints is the one I want it to open, and all I have specified is the prefix I want and the file extension, so it would seem to me like it's finding it just fine if it knows the full file name. Also if I put in a message box between declaring the filename variable and starting the Do While loop, the message box prints the correct filename that I want it to open.
If I save a new file into the folder and name it something like "AA.xls", and then just have the program loop through the folder (rather than specifying the prefix), and then go back and specify the prefix, it works just fine, and continues to work until I close the program and reopen, where the process starts all over. However, this process only works if I save a new file to that folder. If I try to leave the "AA.xls" file in the folder, I get the same error with that file that I get with the others.
Thanks for any input!

Try using a CMD approach and see if you get the same problem, if you do then it's more than likely a permissions issue:
Sub SO()
Const folder As String = "C:\Users\xxx\Documents\Exception Reports\"
Const pref As String = "blah blah prefix"
Dim file As String
Dim exPath As String
Dim fileName As Variant
file = pref & "*.xls": exPath = folder & file
For Each fileName In _
Filter(Split(CreateObject("WScript.Shell").Exec("CMD /C DIR """ & exPath & """ /B /A:-D").StdOut.ReadAll, vbCrLf), ".")
Workbooks.Open CStr(folder & fileName)
'// Do code here
Workbooks(fileName).Close False
Next fileName
End Sub

Related

Hyperlink to open pdf file with variable

I'm currently trying to open an pdf file with variable
There a list of product name, you click on the name and it will open the appropriate pdf file
Its mean that you have to access in a folder, then from the name of the product, you find the pdf file and open it
Here is my code
Sub OpenFile()
Dim filename As String
filename = ActiveCell.FormulaR1C1
'If cell is empty, it don't open nothing
If filename = "" Then
Exit Sub
Else
ActiveWorkbook.FollowHyperlink ("Y:\Logistics\MSDS" & WorksheetFunction.Text(filename) & ".pdf")
The file name i want to open is "1.MSDS-BETACLEAN™ 3510_VN_VN"
The error is in WorksheetFunction.Text(filename), i try to replace it with Workbooks.Open filename and Dir(filename, vbDirectory) but it still didn't work

Open a Workbook with dynamic name

I am working in a project of VBA, and I need to open some Workbooks, but the name is kind of dynamic, but only the last name. Sometimes the name comes like "OnHand 066 May" and sometimes with "OnHand 006 Jun"
Dim Dir As String
Dir = ActiveWorkbook.Path
Do not use Dir as a variable name. It is a reserved function name.
Use a wildcard with the Dir function to find a file that matches.
The Dir function will not return a full path, so you have to append it again if you want to actually open the file.
Let's assume there is only one file in that folder that matches, as you did not specify that in your question.
Dim sFile As String
sFile = Dir(ActiveWorkbook.Path & "\OnHand*.xls*")
If sFile <> "" Then
' if you get an error on the next line, someone else may have it open already
Debug.Print "About to open: " & ActiveWorkBook.Path & "\" & sFile
WorkBooks.Open ActiveWorkBook.Path & "\" & sFile
Else
MsgBox "Cannot find a file like that"
End If

Auto-select all files in a folder to run a macro

I need a macro to automatically loop through files in a folder and copy certain values from these files. I have the copy part setup on manually selected files, but need to now automatically select them.
I already have a macro setup to loop through multiple files that the user selects. Except now, I'm trying to run it automatically and would like the macro to autoselect any files in a specified directory. How do I specify this directory? I've included my current code for manual selection.
Edit: I tried implementing the below answer, but I recieve an error saying that the file list is not in the format of an array. How do I overcome this?
FileNames = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*;*.csv*", MultiSelect:=True)
ii = 1
Do While ii <= UBound(FileName)
Set wbk = Workbooks.Open(FileName(ii))
'Multiple Loops
Wend
Maybe try :
Sub GetAllFileNames()
Dim FolderName As String
Dim FileName As String
FolderName = "C:\Users\sumit\Desktop\Test\" 'change your path
FileName = Dir(FolderName & "*.xls*") 'this one will browse only .xls if you want to browse all file see the note
Do While FileName <> ""
Debug.Print FileName
FileName = Dir()
Loop
End Sub
Note : FileName = Dir(FolderName) will browse you all files in folder.
If the the workbook is in the same folder than the file you want to browse you can select path like this :
FolderName = Application.ActiveWorkbook.Path & "\"

Correctly using GetFolder to grab a path for SaveToFile

I am trying to use GetFolder() to grab a filepath that I can save using save to file and I keep getting a runtime error 3004 write to file failed, the problem is that the file still saves, however it saves outside of the folder that the path should be leading to from the getfolder. The folder I keep grabbing with getfolder is named Test in my documents file. The created document appears with the same name right next to the test folder instead of inside of it. Is this what is supposed to happen?Speaking of how it is named, it has the name of the file which would be test, in front of the name I want so the file is named TestNameIWant, is there something that I can do about this?
Dim BaseDirectory As String
BaseDirectory = GetFolder()
If (BaseDirectory = vbNullString) Then
MsgBox "No Folder Selected" < vbExclamation, "Error"
End If
Set objStream = CreateObject("ADODB.Stream")
objStream.Charset = "iso-8859-1"
objStream.Write("Testing" & vbLf)
projectName = "NameIwant"
FullPath = BaseDirectory & projectName & ".xml"
objStream.SaveToFile FullPath, 1
objStream.Close
I am expecting the file to save to a specific location and I keep getting Run Time Error 3004 Write To File Failed.

Excel VBA - Check if file exists using Wildcard and open the file

I wish to check whether a file exist in a folder on my computer. I have below, which can see if a specific file exists:
Function FileExists(sFile As String)
sPath = "M:\User\" & sFile & ".xlsm"
FileExists = Dir(sPath) <> ""
End Function
However, my files are named like: Filename - Version xx.xlsm and is updated regularly. Please note that there will only be one file in the folder, but the filename can vary.
How can I search in the folder using wildcard:
Filename - Version % % and then, if it find any file, open the file afterwards?
One option would be to Open the file inside of the FileExists function. However, I would not recommend doing this. The function should do exactly what the name implies and nothing more.
Another option is restructure your code a little bit:
Private Sub OpenFile()
Dim FileName As String
FileName = GetFile("Filename - Version*")
If FileName <> "" Then
'open FileName as needed
End If
End Sub
Private Function GetFile(sFile As String) As String
sPath = "M:\User\" & sFile & ".xlsm"
GetFile = Dir(sPath)
End Function

Resources