在Excel VBA中两次运行相同的代码时,无法获得OLEObjects属性错误

时间:2018-09-05 09:53:57

标签: excel vba excel-vba

我在多个命令行中运行相同的代码行,这些命令按钮打开了嵌入在父电子表格中的已分配excel模板。

Private Sub M113_Click()
Dim WDObj As Object
Dim WDApp As Object
Dim str As String

str = ActiveWorkbook.Path & "\CND Scaled Template.xlsm"

Set WDObj = Sheets(2).OLEObjects("CNDS")
WDObj.Verb xlOpen

Dim i As Integer
i = Workbooks.Count

Workbooks(i).SaveCopyAs str
Workbooks(i).Close

Workbooks.Open (str)

Set WDObj = Nothing
Set WDApp = Nothing
End Sub

这是我收到错误消息“无法获取工作表类的OLEObjects属性”的行

Set WDObj = Sheets(2).OLEObjects("CNDS")

打开excel后第一次运行它并没有给出任何错误,但是第二次运行却是问题。通过调试模式进入VBA编辑器并按F5也可以正常工作,并且整个代码执行良好。可能是什么问题?同样,除excel以外的Ole对象也不会发生这种情况。

1 个答案:

答案 0 :(得分:0)

这是您修改后的代码:

Private Sub M113_Click()

    Dim WDObj As Object
    Dim WDApp As Object
    Dim str As String

    With ThisWorkbook
        str = .Path & "\CND Scaled Template.xlsm"
        Set WDObj = .Worksheets(2).OLEObjects("CNDS")
        WDObj.Verb xlOpen
    End With

    Dim i As Long
    i = Workbooks.Count
    Workbooks(i).SaveCopyAs str
    Workbooks(i).Close
    Workbooks.Open str

End Sub

如@PEH的评论中所述,最有可能的错误在于引用ThisWorkbookActiveWorkbook

我删除了Set WDObj = Nothing,因为它们是局部变量,并且在结束后仍然会被销毁。

Why Use Integer Instead of Long?