vba 代码在 1 个远程桌面中给出错误,但在其他远程桌面中有效

问题描述 投票: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

设置 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个回答
0
投票

如果您使用的是非最新 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.