首页 > 解决方案 > 运行时错误;自动化错误;使用 UIAutomation 的 VBA 中的未指定错误

问题描述

它以前可以工作,但现在当我在 sub 的第 12 行设置 oElements 时,我不断收到错误代码“自动化错误;未指定错误”。有什么想法吗?

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

我的参考是

标签: excelvbaui-automation

解决方案


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

假设您正在寻找“另存为”对话框(然后是其中的文件路径文本字段)。

遍历 rootelement.children,并查找“另存为”窗口的所有者。因此,如果所有者是 Internet Explorer 浏览器,请检查 rootelement.children 中是否有 UIA_Nameproperty(如“*Internet Explorer”)。然后在他们的后代中搜索 SaveAs 框。

或者,尝试在设置 oElements 时添加不同的条件,以获取具有 windowpattern 的条件:

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

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


推荐阅读