运行-时间错误;自动化错误;使用 UIAutomation VBA 中的未指定错误

Run-time error; Automation Error; Unspecified Error in VBA using UIAutomation

它之前工作正常,但现在我在子的第 12 行设置 oElements 时不断收到错误代码 "Automation Error; Unspecified Error"。有什么想法吗?

Sub SavePath(ByVal strWindowID As String, ByVal strObjectName As String, ByVal strAutomationId As String, ByVal strLocalizeType As String, ByVal strValue As String)

Dim intElementCounter As Integer
Dim strTreeItem1 As String
Dim strTreeitem2 As String
Dim strTreeitem3 As String

strThiswbFileName = ActiveWorkbook.Name
strThiswbCaption = Application.Caption

Set oTW = oAutomation.ControlViewWalker
Set oCondition = oAutomation.CreatePropertyCondition(UIAutomationClient.UIA_NamePropertyId, strObjectName)
Set oElements = oAutomation.GetRootElement.FindAll(TreeScope_Descendants, oCondition)

For intElementCounter = 0 To oElements.length - 1
    If oElements.GetElement(intElementCounter).CurrentName = strObjectName Then
        If oElements.GetElement(intElementCounter).CurrentAutomationId = strAutomationId Then
            If oElements.GetElement(intElementCounter).CurrentLocalizedControlType = strLocalizeType Then
                Set oPatternValue = oElements.GetElement(intElementCounter).GetCurrentPattern(UIAutomationClient.UIA_ValuePatternId)
                oPatternValue.SetValue strValue
                Exit Sub
            End If
        End If
    End If
Next
End Sub

我的参考资料是

请勿随意使用 RootElement 中的 treescope_descendants! 我不知道为什么,但 FindAll 函数可能会出错,通常是在遍历根的后代时。

假设您要查找 'Save As' 对话框(然后是其中的文件路径文本字段)。

遍历 rootelement.children,寻找 'Save As' window 的所有者。因此,如果所有者是 Internet Explorer 浏览器,则检查 rootelement.children 是否有 UIA_Nameproperty,如“*Internet Explorer”。然后在其后代中搜索“另存为”框。

或者,尝试在设置 oElements 时添加不同的条件,从而获得具有 window 模式的元素:

Set oCondition = oAutomation.CreatePropertyCondition(UIAutomationClient.UIA_IsWindowPatternAvailablePropertyId, True)

您已经在第一个 if 块中再次检查 nameproperty