运行时错误 9:在一个远程桌面中下标超出范围,但在其他远程桌面中则不然

问题描述 投票:0回答:1

我的宏适用于除一个之外的所有(必需)远程桌面。

这让我相信我的代码没问题。

wsCurrentworksheet.Active
File = Cells(7, 4)
Path = Cells(7, 5)

ChDrive Left(Path, 1)
ChDir Path

Set wbMyWorkbook = Workbooks.Open(FileName:=File, UpdateLinks:=False, ReadOnly:=True)
wbMyWorkbook.Activate
Set wsMyWorksheet = wbMyWorkbook.Worksheets("Sheet1") '*gives runtime error 9*
wsMyWorksheet.Activate

Set wsMyWorksheet
线给出

运行时错误9:下标超出范围

我知道路径没问题,因为它确实打开了被调用的工作簿。

一个临时且低效的“修复”是将这部分代码重复两次:

Set wbMyWorkbook = Workbooks.Open(FileName:=File, UpdateLinks:=False, ReadOnly:=True)
wbMyWorkbook.Activate

Set wbMyWorkbook = Workbooks.Open(FileName:=File, UpdateLinks:=False, ReadOnly:=True)
wbMyWorkbook.Activate

Set wsMyWorksheet = wbMyWorkbook.Worksheets("Sheet1")
wsMyWorksheet.Activate

这告诉我什么?我该如何解决它?

excel vba
1个回答
1
投票

如果您使用的是非最新 Excel 版本,这是一种更安全的方法:

    Dim wbMyWorkbook As Workbook, wbPath As String, wbName As String
    
    wbPath = "C:\Temp\"   'for example
    wbName = "Data.xlsx"  'include the extension
    
    On Error Resume Next 'ignore error if not open
    Set wbMyWorkbook = Workbooks(wbName) 'already open?
    On Error GoTo 0      'stop ignoring errors
    
    If wbMyWorkbook Is Nothing Then 'if not already open then open it
        'no need for ChDrive/ChDir if you use the full path
        Set wbMyWorkbook = Workbooks.Open(Filename:=wbPath & wbName, _
                                   UpdateLinks:=False, ReadOnly:=True)
    End If
© www.soinside.com 2019 - 2024. All rights reserved.