VBA搭配Selenium操作Chrome:仅在VBA层实现错误处理的相关问题
VBA Selenium 错误处理实现方案
核心修改说明
- 配置Selenium隐式等待超时(默认10秒),触发卡顿/找不到元素等异常时自动进入错误处理流程
- 新增Alert弹窗检测逻辑,匹配网页表单校验不通过弹出
Alert pop的触发场景 - 新增
PatientName_Start行标记,错误处理完成后可直接跳转回该步骤重新执行 - 新增Excel执行状态标记:默认使用第7列(G列)记录结果,成功写
Done,失败写Not Done,列号可自行调整 - 错误处理流程严格匹配需求:刷新页面→关闭Alert弹窗→跳转重跑
完整代码
Sub Automate() Dim bot As WebDriver Dim row As Long ' 请自行替换为实际遍历的行号/新增循环逻辑 Dim ListDD As Object ' 初始化浏览器配置 Set bot = New WebDriver bot.Start "chrome" bot.Get "/" ' 配置10秒隐式等待,卡顿超时时自动触发错误,单位为毫秒 bot.Timeouts.ImplicitWait = 10000 ' 错误捕获,触发异常时跳转到ErrorHandler分支 On Error GoTo ErrorHandler '===================== 重跑入口 ===================== PatientName_Start: '#Patient Name bot.FindElementByName("patient_name").SendKeys "Value" ' 每次操作后检测是否弹出校验Alert If CheckAlert(bot) Then GoTo ErrorHandler '#Age-in If Sheet1.Cells(row, 4) = "Years" Then bot.FindElementById("age_year").Click bot.FindElementByName("age").SendKeys "Value" ElseIf Sheet1.Cells(row, 4) = "Months" Then bot.FindElementById("age_month").Click bot.FindElementByName("age").SendKeys "Value" ElseIf Sheet1.Cells(row, 4) = "Days" Then bot.FindElementById("age_day").Click bot.FindElementByName("age").SendKeys "Value" End If If CheckAlert(bot) Then GoTo ErrorHandler '#Mobile Number bot.FindElementById("contact_number").SendKeys "Value" If CheckAlert(bot) Then GoTo ErrorHandler '#Gender If Sheet1.Cells(row, 6) = "Male" Then Set ListDD = bot.FindElementById("gender") ListDD.AsSelect.SelectByText "Value" ElseIf Sheet1.Cells(row, 6) = "Female" Then Set ListDD = bot.FindElementById("gender") ListDD.AsSelect.SelectByText "Value" ElseIf Sheet1.Cells(row, 6) = "Transgender" Then Set ListDD = bot.FindElementById("gender") ListDD.AsSelect.SelectByText "Value" End If If CheckAlert(bot) Then GoTo ErrorHandler ' 所有步骤执行完成,标记为Done Sheet1.Cells(row, 7) = "Done" ' 正常结束流程,可根据需求加后续逻辑(比如处理下一行数据) GoTo FinalExit '===================== 错误处理分支 ===================== ErrorHandler: ' 标记当前行执行失败 Sheet1.Cells(row, 7) = "Not Done" ' 按需求顺序执行错误处理操作 bot.Refresh ' 检测是否存在Alert,存在才点击确认避免报错 If CheckAlert(bot) Then bot.SwitchToAlert.Accept End If ' 跳转回Patient Name步骤重新执行 Resume PatientName_Start '===================== 最终退出分支 ===================== FinalExit: bot.Quit Set bot = Nothing End Sub ' 自定义函数:检测当前页面是否存在Alert弹窗 Function CheckAlert(bot As WebDriver) As Boolean On Error Resume Next Dim alertText As String alertText = bot.SwitchToAlert.Text ' 无错误说明存在Alert,返回True CheckAlert = (Err.Number = 0) Err.Clear End Function
注意事项
- 代码中
row变量需要替换为你实际遍历的行号,若需要批量处理多行数据,可自行在外层加行循环逻辑 - 状态标记默认使用第7列(G列),可自行修改
Sheet1.Cells(row, 7)中的列号匹配你的表格结构 - 隐式等待超时时间可按需修改
bot.Timeouts.ImplicitWait的数值调整
内容的提问来源于stack exchange,提问作者Joseph John
相关产品推荐
相关产品推荐

