Excel VBA-不能从set字段加载文件

我已经将我的工作表设置为具有参数部分,以便用户可以设置工作表,然后只更新特定区域。 其中两个参数是外部文件,即“黑匣子”计算模块。

这些设置与他们的完整path,并存储在工作表上的单元格。

在开始计算过程中,它们将被加载下面的代码

'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 

我遇到的问题是,当我运行的代码说,该文件没有find。 如果我去,通过重新select文件重新设置参数表中的字段(我是一个filedialog设置来做到这一点),然后代码完美工作,文件打开。 从本质上讲,这意味着在每次closures表格之后,文件在计算运行之前已经被重新分配。 任何人都知道这可能是什么原因?

在你的代码行中

 Set wbTarget = Workbooks.Open(NameOfFile, UpdateLinks:=False) 

你只指定文件名,没有path。 这将尝试从当前path打开文件,这可能不是预期的path。 一旦你使用了OpenFile对话框并浏览你的文件,当前path就会被更新,然后代码就可以工作。

你可能的意思

 Set wbTarget = Workbooks.Open(completefilepath , UpdateLinks:=False)