I have set my sheet up to have a parameters section so users can set-up the sheet and then just update specific areas. Two of the parameters are external files which are “black box” calculation modules.
These are setup with their full paths and stored in a cell on the sheet.
On starting the calculation procedure they get loaded with the following code
'Set file name and location. NameOfFile = ActiveWorkbook.Worksheets("Parameters").Cells(8, 2).Value PathToFile = Left$(NameOfFile, InStrRev(NameOfFile, "\") - 1) FileNameNoPath = Mid$(NameOfFile, InStrRev(NameOfFile, "\") + 1) NameOfFile = FileNameNoPath
completefilepath = PathToFile & "\" & NameOfFile
'set the target workbook to a variable. If an error is
'generated, then the workbook is not open, so open it
On Error Resume Next
Set wbTarget = Workbooks(NameOfFile)
If Err.Number <> 0 Then
'Open the workbook
Err.Clear
Set wbTarget = Workbooks.Open(NameOfFile, UpdateLinks:=False)
CloseIt = True
End If
'Check and make sure workbook was opened
If Err.Number = 1004 Then
MsgBox "Sorry, but the file you specified does not exist!" _
& vbNewLine & NameOfFile
Exit Sub
End If
The problem I am having is that when I run the code it says the file is not found. If I go, reset the field in the parameters sheet by reselecting the file (I hae a filedialog set-up to do this), then the code works perfectly and the file opens. Essentially this means that after every time the sheet is shut down, the file has tp be reselcted before the calculations are run. Anyone know what could be causign this?
In your line of code
you are specifying file name only, no path. This will try to open the file from the current path, which may not be the intended path. Once you have used the
OpenFiledialog and browsed to your file, the Current Path is updated and the code then works.You probably meant