0

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

这些设置了完整的路径并存储在工作表上的单元格中。

在开始计算过程时,它们会加载以下代码

 '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

我遇到的问题是,当我运行代码时,它说找不到文件。如果我去,通过重新选择文件来重置参数表中的字段(我有一个文件对话框设置来执行此操作),然后代码完美运行并且文件打开。从本质上讲,这意味着每次关闭工作表后,都会在运行计算之前重新选择文件。有谁知道这可能是什么原因?

4

1 回答 1

2

在您的代码行中

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

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

你可能是说

Set wbTarget = Workbooks.Open(completefilepath , UpdateLinks:=False)
于 2012-09-25T09:02:20.283 回答