新版SolidWorks中GetObject错误

GetObject error in new version of SolidWorks

我有一个用户在 2018 年从网上复制了一个宏。升级到2020后宏无法通过第一行;

Set swApp = GetObject(,"Application.SldWorks")

错误是

Run-time error '429' ActiveX component can't create object

我尝试重置库并浏览了多个论坛帖子以寻找解决方案。 This post 最接近我的问题。

下面是完整代码;

Dim swApp As SldWorks.SldWorks

Public Sub main()

    Set swApp = GetObject(,"Application.SldWorks")

    Dim ActiveDoc As ModelDoc2
    Set ActiveDoc = GetObject(, "Sldworks.Application").ActiveDoc

    If Not ActiveDoc Is Nothing Then
        If ActiveDoc.GetType = 2 Then
            GoTo Traverse
        End If
    End If
    MsgBox ("This macro should be run, with an open assembly as the active document.")
    Exit Sub

Traverse:
            
    Dim myModel As ModelDoc2
    Set myModel = ActiveDoc
    Call Traverse(myModel, myModel.ConfigurationManager.ActiveConfiguration.Name)

    MsgBox ("Done")

End Sub

您不应该使用像 ActiveDoc 这样的保留名称作为变量名。您不需要对宿主已直接引用的对象使用 GetObject。你不再需要 Call

如果我使用那里的 GetObject 命令,我只会收到您看到的错误。

我已经在 SolidWorks 2020 中测试了这段代码:

Option Explicit

Dim swApp As Object

Sub main()    
    Set swApp = Application.SldWorks
    Dim thisDoc As ModelDoc2
    Set thisDoc = swApp.ActiveDoc
    If Not thisDoc Is Nothing Then
        If thisDoc.GetType = 2 Then
            Dim myModel As ModelDoc2
            Set myModel = thisDoc
            Traverse myModel, myModel.ConfigurationManager.ActiveConfiguration.Name
            MsgBox "Done"
            Exit Sub
        End If
    End If
    
    MsgBox "This macro should be run, with an open assembly as the active document."
End Sub