VBA编写WhatsApp自动化脚本出现编译语法错误如何解决?
问题原因
- 直接原因:VBA字符串语法规则要求,字符串内部的双引号必须用两个连续双引号转义。你报错的行中XPath表达式里的
@id="side"直接使用了单个双引号,VBA会将@id=后的双引号识别为整个字符串的结束标记,后续的side部分不符合VBA语法,因此触发编译错误。 - 隐藏问题:代码中
End(x1Up)的参数是数字1而非小写字母L,修正语法错误后运行时也会抛出异常,需要同步修改。
修复方案
1. 修正报错行的XPath字符串
将原报错行:bot.FindElementByXPath("//*[@id="side"]/div[1]/div/label/div/div[2]").Click
修改为:bot.FindElementByXPath("//*[@id=""side""]/div[1]/div/label/div/div[2]").Click
2. 修正行号统计参数
将:lastrow = Cells(Rows.Count, 1).End(x1Up).Row
修改为:lastrow = Cells(Rows.Count, 1).End(xlUp).Row
修复后完整代码
Sub WebWhatsApp() 'Activate Selenium Type Library: Tools > Reference Dim bot As New WebDriver Dim ks As New Keys 'Init New Chrome instance & navigate to WebWhatsApp bot.Start "chrome", "http://web.whatsapp.com/" bot.Get "/" 'Ask user to scan the QR code. Once logged in, continue with macro MsgBox "Please scan the QR code. After you are logged in, please confirm this message box by clicking" 'Determinate number of messages by identifying the number of last rows in column A lastrow = Cells(Rows.Count, 1).End(xlUp).Row 'Search phonenumber/name, press enter, paste text into WebWhatsApp, press Enter to send message For i = 2 To lastrow 'Get search text (phone number or name) from worksheet searchtext = Sheets(1).Range("A" & i).Value 'Get textmessage from worksheet textmessage = Sheets(1).Range("B" & i).Value 'click in the searchbox bot.FindElementByXPath("//*[@id=""side""]/div[1]/div/label/div/div[2]").Click 'Wait 500 ms bot.Wait (500) 'Insert search text(phone number or name) bot.SendKeys (searchtext) 'Wait 500 ms bot.Wait (500) 'Press Enter to confirm search text bot.SendKeys (ks.Enter) 'Wait 500 ms bot.Wait (500) 'Load message into WebWhatsApp bot.SendKeys (textmessage) 'Wait 500 ms bot.Wait (500) 'Press Enter to send the message bot.SendKeys (ks.Enter) Next i 'Get notification once done, MsgBox "Done :)" End Sub
注意:WhatsApp网页版的前端元素结构会定期更新,若后续运行出现元素找不到的报错,重新提取搜索框的最新XPath替换即可。
内容的提问来源于stack exchange,提问作者kdb014
相关产品推荐
相关产品推荐

