问题:
在微软宣布停止对IE的支持后,许多使用VBA中Web Browser的用户遇到了困境,因为Web Browser使用的IE内核。然而微软并没有给出支持Edge的新版Web Browser,网上许多第三方的库也不够完善。
解决方案:
经过调研,libEdge可以较好的和VBA集成,实现在Excel中打开Browser,甚至能够通过执行js代码,获取web页面的信息。
https://github.com/bubdm/libEdge/tree/main/VBA_libEdge
注意:
项目需要WebView2Loader.dll和LibEdge.dll两个库,区分x86和x64版本。
示例代码:
Public Function GetEncodedCookieFromWebBrowser(serverIP As String) As StringDim url As StringDim encodedCookie As StringDim isValidIPFormat As BooleanDim jsResult As StringDim path As StringencodedCookie = ""url = "https://" + serverIP + "/proj/demo/" + Guid()isValidIPFormat = IsValidIP(serverIP)path = Application.ActiveWorkbook.path & "\"ChDir pathIf isValidIPFormat = False ThenIf VBA_StartEdge() <> 0 Then Exit FunctionVBA_Navigate url' Wait for the page to fully loadDo While Not PageLoadedSleep 500 ' Sleep for 500 milliseconds to allow user interactionDoEventsLoop' Wait until the cookie contains 'token%22'Do Until InStr(jsResult, "token%22") > 0If VBA_RunJavascript("document.cookie", jsResult) <> 0 ThenVBA_StopEdge TrueExit FunctionEnd IfSleep 500 ' Sleep for 500 milliseconds to allow user interactionDoEventsLoopencodedCookie = jsResultVBA_StopEdge TrueEnd IfGetEncodedCookieFromWebBrowser = encodedCookie
End Function