2015-04-02 63 views
1
Dim savepath as String 
Dim dfile as String 
Dim wb as Workbook 

'strings setting omitted 

If Not Dir(savepath & dfile) <> "" Then 
    MsgBox "Cannot find the file." 
End If 

Set wb = Workbooks(savepath & dfile) 
wb.Open 
'Workbooks(savepath & dfile).Open also fails 

尽管Dir()没有提高消息框,但我得到运行时错误9。我可以将连接字符串复制并粘贴到Windows资源管理器栏中,并打开excel文件,因此文件当然存在。Workbooks.Open方法在文件存在时给出运行时间9(Dir(file_string)有效)

任何想法?

+0

为什么要省略字符串设置?我们如何知道你是否有这些正确的? – Davesexcel 2015-04-02 21:20:45

+0

Workbooks集合只包含* open *工作簿。 – 2015-04-02 21:22:41

回答

0

我会建议主要是改变你的代码中,如果条件:

Dim savepath as String 
Dim dfile as String 
Dim wb as Workbook 

'strings setting omitted 

strFilename = Dir(savepath & dfile) 
If Len(strFilename) > 0 Then 
    Set wb = Workbooks.Open(savepath & dfile) 
Else 
    MsgBox "Cannot find the file " & dfile & " in " & savepath & "." 
End If 

这种方式,您还保证,当文件确实存在Open只发生,我认为把积极的情况下,在顶部和错误底部更具可读性。

你也可以写

If Dir(savepath & dfile) <> "" Then 

但对于代码的快速简要回顾,像NOT fn() <> ""是不是可以理解

+0

'wb.Open'不是VBA中的东西 – 2015-04-02 21:27:11

+0

复制粘贴错误,谢谢,更正 – 2015-04-02 21:47:18

2

Workbooks仅包括打开的工作簿。打开您使用的工作簿Workbooks.Open(pathToFile)

Dim savepath as String 
Dim dfile as String 
Dim wb as Workbook 

'strings setting omitted 

If Dir(savepath & dfile) = "" Then 
     MsgBox "Cannot find the file." 
Else 
     Set wb = Workbooks.Open(savepath & dfile) 
End If 
相关问题