I am trying to use VBA to open a .xls file in a specific directory but am unable to do so because of a VBA run-time error. I need to use a wildcard in the path because the filename changes slightly month-to-month, but it always begins with "CB947." I need to copy data from the CB947 workbook into my Master workbook. Here's what I have so far:
Dim dpath, sFound As String
dpath = "C:\Users\gbrown\OneDrive - My Company\REVPRO\Input Data\2018\January\"
Set Master = ThisWorkbook
sFound = Dir(dpath & "\CB947*.xls")
Debug.Print dpath & sFound
If (sFound <> "") Then
Workbooks.Open dpath & sFound
End If
When I get to the Debug.print command above, the Immediate window prints out the correct path and filename, so I know the script is locating the correct file. It just isn't able to open it. When I try and run the above code, I get the following error:
Is my DIR sytax incorrect or am I missing something else?
EDIT: here's what my Debug.Print command shows in the Immediate window:
C:\Users\gbrown\OneDrive - My Company\REVPRO\Input Data\2018\
January\CB947 (4).xls
Turn on Option Explicit
You can't declare variables that way, dpath is a variant
You have two slashes in your path
Let's add vbNormal to your Dir call, just in case
THIS WORKED FOR ME:
Dim dpath As String
Dim sFound As String
dpath = "C:\Users\gbrown\OneDrive - My Company\REVPRO\Input Data\2018\January\"
sFound = Dir(dpath & "CB947*.xls", vbNormal)
Debug.Print dpath & sFound
If (sFound <> "") Then
Workbooks.Open dpath & sFound
End If
NOTE: If this isn't working for you, then there might be a permissions issue. The workbook might be locked or unavailable to be opened for some filesystem reason.
Related
I am trying to open file from the same folder as the main workbook. The problem is that the name is not permanent and just one word stays always inside the name - "NAME".
I want to use specific method with Thisworkbook.Path to open the xlsx file but it is not finding the workbook with the code.
that is the relavant part of code:
Sub RemoveDuplicats()
Dim Harel As Workbook
Dim SAP As Workbook
Dim Path As String
Dim Found As String
Path = ThisWorkbook.Path
Found = Dir(Path & "*NAME*.xlsx") 'open SAP report
If Found <> "" Then
Set SAP = Workbooks.Open(Path & Found)
End If
End Sub
ThisWorkbook.Path Returns the path without trailing backslash,
try
Found = Dir ( Path & "\" & "*NAME*.xlsx")
You would need to Loop though all Fiels in this Folder and compare the File Names like this:
Dim StrFile As String
StrFile = Dir(ThisWorkbook.Path & "\*" & ".xlsm")
Do While Len(StrFile) > 0
If StrFile Like "*Name*" Then
MsgBox StrFile 'This will be your File
End If
StrFile = Dir
Loop
while running this code its showing bad file name or number
I have stored all my files in "\C:\Users\20098323\Desktop\EXCL\"
Sub ProcessFiles()
Dim Filename, Pathname As String
Dim wb As Workbook
Pathname = ActiveWorkbook.Path & "\C:\Users\20098323\Desktop\EXCL\"
Filename = Dir(Pathname & "*.xlsx")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
DoWork wb
wb.Close SaveChanges:=True
Filename = Dir()
Loop
End Sub
Sub DoWork(wb As Workbook)
With wb
'Do your work here
.Worksheets(1).Range("A1").Value = "Hello World!"
End With
End Sub
Remove ActiveWorkbook.Path & and the first \ from the line Pathname = ActiveWorkbook.Path & "\C:\Users\20098323\Desktop\EXCL\"
Pathname = "C:\Users\20098323\Desktop\EXCL\"
ActiveWorkbook.Path & "\C:\Users\20098323\Desktop\EXCL\"
This is your problem. It appends the path to the EXCL folder to the path of your current workbook. So you will end up with something like C:\wherever\you\have\your\workbook\C:\Users\20098323\Desktop\EXCL\. Instead use
Pathname = "C:\Users\20098323\Desktop\EXCL\"
Here's a tip for the future: If it gives you an error, press the debug button and it will show you the line where the error occurred. Then you can hover over the variable names and see their current value.
I've made an Excel sheet which processes data to a Sheet and Saves it as a new workbook in a certain Folder - Subfolder (named like the first part of the file names).
The code works fine but I'd like to make a new folder if the required path does not exists. Should definitely be possible to achieve with an 'If' function, but I don't know how to create new folders.
Note: skipped some part in the code below, to keep it short I only past the parts worth mentioning.
Sub SaveSheetAs()
Dim sMainFolder as String
Dim sFileName as string
Dim sSubFolder as string
sMainFolder = Z:\Parts Manufacturing\5. Kwaliteit\130 - in proces meten\EindProject\Bron '(Main folder, which isn't variable)
sFileName = 4022 646 68954#1234 '(Part name with Unique number)'variable number, in de real code this number is received by refering to a range("")
sSubFolder = 4022 646 68954 '(variable number, in de real code this number is received by refering to a range("")
ActiveWorkbook.SaveAs Filename:=sMainFolder & "\"& sSubFolder & "\" & sFileName & ".csv", FileFormat:=xlCSV, CreateBackup:=False, Local:=True
end sub
Here you go :
If Dir(sMainFolder & "\"& sSubFolder & "\", 16) <> vbNullString Then
Else
MkDir (sMainFolder & "\"& sSubFolder & "\")
End If
I'm doing a check to make sure that my code is able to see my file before I move to the next step of my program. This is my code, but it always displays as the path not existing. Did I do something wrong?
Sub NewNameiLoop()
Dim i As Double
Dim NameStr As String
Dim NewNamePath As String
NameStr = Renamer.New_Name.Text
NewNamePath = Renamer.Path_Text.Text & "\" + NameStr & "-" & Right("00" & i, 3) & ".ipt"
Do While i < 99 'Counts with the file name up to -099
i = i + 1
If vbOK Then
MsgBox (Renamer.Path_Text.Text & "\" + NameStr & "-" & Right("00" & i, 3))
If Dir(NewNamePath) <> "" Then
MsgBox "Path Exists."
Else: MsgBox "Path does not exist."
End If
Else: Exit Sub
End If
Loop
End Sub
Other information:
This code is in the module NewNameLoop in the sub NewNameiLoop.
The form it goes to is called Renamer. The form calls NewNameiLoop when the user clicks "Apply" to rename some files. After they are renamed, they call this code to check for the file's existence.
The MsgBox displayed contains the full, correct path.
This is in Autodesk Inventor, not Excel! Thus far, the coding has been pretty much the same. No weird quirks or anything.
JPEGs of what is happening. As explained below, I AM able to access C:\ and things within C:. The first parts of my program make a whole new folder and copy a different folder's contents in to it. After that it goes to the original folder and renames all the files. So does that mean it is indeed a coding problem? No one seems to know.
The Dir will return nothing if:
1) The .ipt file does not exists or the file name is different from what you coded
2) No access to the folder
If you are not concern with the filename I suggest to leave the NewNamepath as Renamer.Path_Text.Text & "\" and do a file search in this path for the file you are looking for
Yes, apparently you can't do a 'Dir' on that folder. But you can use FileSystemObject.
Add a Project reference to "Microsoft Scripting Runtime"
Then adapt the following approach:
Dim oFSO As FileSystemObject
Set oFSO = New FileSystemObject
If oFSO.FileExists(NewNamePath) Then
Debug.Print "Found it"
Else
Debug.Print "Not Found"
End If
Set oFSO = Nothing
I have been assigned the task of developing a excel document that whole office will use. The user will click a button and the macro will export the file as a PDF to a shared folder. I wrote this code and tested this code using excel 2010. People that have excel 2007 where getting an error message saying "Run Time Error 1004 Document not saved. This document may be open, or an error may have been encountered when saving." I looked into the problem a little bit and found that excel 2007 needed an add-in update, so I installed it on their computers. I also checked to see if they have adobe on their computers and they do. They are still having the problem and I am unsure of what to do. Any help would be greatly appreciated!
Here is my code
' Define all variables
Dim strFileName As String
Dim folder As String
Dim member As Integer
Dim member_count As Integer
Dim member_name As String
Dim show As Variant
Dim MyTime As String
'Save as new file
Worksheets("Input data").Visible = True
folder = Sheets("Input data").Range("location").Value
MyTime = Time
Sheets("Input data").Select
Range("G2").Value = MyTime
strFileName = folder & "Material Request - " & Sheets("Input data").Range("name").Value & "_" & Sheets("Input data").Range("date").Value & " " & Sheets("Input data").Range("time").Value & ".pdf"
Sheets("Material Request").Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName 'OpenAfterPublish:=True`
You should start with changing the code to remove .Select & .ActiveSheet instances.
Dim oWS as Worksheet
Set oWS = ThisWorkbook.Worksheets("Input data")
' Worksheets("Input data").Visible = True
folder = oWS.Range("location").Value
If Right(folder,1) <> Application.PathSeparator Then folder = folder & Application.PathSeparator
MyTime = Time
' Sheets("Input data").Select
oWS.Range("G2").Value = MyTime
strFileName = folder & "Material Request - " & oWS.Range("name").Value & "_" & oWS.Range("date").Value & " " & oWS.Range("time").Value & ".pdf"
Debug.Print "strFileName: " & strFileName
'Sheets("Material Request").Select
oWS.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName 'OpenAfterPublish:=True`
Set oWS = Nothing
Refer to this MSDN Worksheet.ExportAsFixedFormat Method, you may need fill in more parameters depending on properties of the Worksheet "Input Data".
I have added some checks and refer to Immediate window to check value of strFileName in 2007.
I had a similiar problem (Error 1004 when attempting export). After an hour of pulling my hair out, here was the source of my problem.
I was passing a cell value as part of generating the filename. I was doing this in the format of
fileName:= ActiveWorkbook.Path & "\" & CStr(Workbooks.Cells(i,j).Value) & ".pdf"
The text in the cell itself was formatted to be in two rows (i.e. "top row text" + (Alt+K) + "bottom row text"). While the string looks normal in Debug.print, MsgBox, or value previews, I am thinking that there is a hidden character which encodes the new line for the cell. I believe this hidden character causes the error when passed as part of the fileName argument. I'm guessing Excel doesn't pick it up but the OS's file name system does.
In any case, this fixed the issue for me.