定义工作簿时运行时错误(9)

时间:2017-07-21 13:55:27

标签: excel-vba vba excel

早上好,

我尝试使用我的主excel工作簿阅读另一本工作簿。 每当我尝试将该工作簿设置为变量(book2)时,我都会收到错误"运行时错误9:下标超出范围"。 这里是我写的代码:

Const path As String = "\\prod\root\v_drive\IBS\ENG_Data\Jobs\NOETIX_EXPORT_FOR_COMMUNICATION_TOOL\PPM TOOL - Order Level.xls"

Sub Import_Data()
Dim lookFor As String
Dim srchRange As Range
Dim book1 As Workbook: Set book1 = ThisWorkbook
Dim book2 As Workbook: Set book2 = Workbooks(path)
End sub

如果不是给出错误的行而是输入代码

Workbooks.Open (path)

文件打开没有任何问题(这应该意味着路径是正确的,文件存在..)。我尝试打开和关闭文件,在我的本地驱动器或远程位置,但我一直有同样的错误。 你知道我可能做错了什么吗? 在此先感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

尝试下面的代码,代码中的解释为注释:

Option Explicit

Const path As String = "\\prod\root\v_drive\IBS\ENG_Data\Jobs\NOETIX_EXPORT_FOR_COMMUNICATION_TOOL\PPM TOOL - Order Level.xls"

Sub Import_Data()

Dim lookFor As String
Dim srchRange As Range
Dim ClnFileName As String
Dim book1 As Workbook
Dim book2 As Workbook

Set book1 = ThisWorkbook
' get the clean file name (without the path)
ClnFileName = Mid(path, InStrRev(path, "\") + 1)

On Error Resume Next
Set book2 = Workbooks(ClnFileName) ' try to set the workbook (if it's open)
On Error GoTo 0
If book2 Is Nothing Then
    Set book2 = Workbooks.Open(path)
End If

End Sub

答案 1 :(得分:0)

方法Workbooks不接受文件的路径作为参数。它只接受索引或工作簿的名称(即它们需要打开)。

在[1]中查看更多内容:https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbook-object-excel