VBA is a very popular programming language mainly used for the implementation of automation functions and tasks in Microsoft Office. JavaScript is a very flexible scripting language that is often used in front-end web development. In some scenarios, we need to call JavaScript in VBA. This article will introduce two methods of executing JavaScript in VBA.
Method 1: WebBrowser control
The WebBrowser control is a control used in VBA to display Web content. It can open a specified URL, obtain web page content, etc. In addition to this, it can also execute JavaScript code. The following is a sample code:
Sub RunJavaScriptWithWebBrowser()
Dim oBrowser As Object Set oBrowser = CreateObject("InternetExplorer.Application") '打开网页 oBrowser.Visible = True oBrowser.Navigate "https://www.baidu.com/" '等待页面加载完成 Do While oBrowser.ReadyState <> 4 DoEvents Loop '执行 JavaScript oBrowser.Document.parentWindow.execScript "document.title='VBA 调用 JavaScript'", "JavaScript" '关闭浏览器 oBrowser.Quit Set oBrowser = Nothing
End Sub
In this sample code, we open the Baidu search page by creating an InternetExplorer.Application object. After the page is loaded, a JavaScript statement is executed through the Document.parentWindow.execScript method, and the title of the web page is changed to "VBA calls JavaScript".
It should be noted that when using the WebBrowser control to call JavaScript, you need to wait for the page to be loaded, otherwise the JavaScript may not be executed.
Method 2: IE instance
In addition to the WebBrowser control, we can also call JavaScript by creating an IE instance. The following is a sample code:
Sub RunJavaScriptWithIE()
Dim oIE As Object Set oIE = CreateObject("InternetExplorer.Application") '打开网页 oIE.Visible = True oIE.Navigate "https://www.baidu.com/" '等待页面加载完成 Do While oIE.ReadyState <> 4 DoEvents Loop '获取页面对象 Dim oDoc As Object Set oDoc = oIE.document '执行 JavaScript oDoc.parentWindow.execScript "document.title='VBA 调用 JavaScript'", "JavaScript" '关闭浏览器 oIE.Quit Set oIE = Nothing
End Sub
In this sample code, we first create an IE instance and open Baidu search page. Then the page object is obtained through oIE.document, and a JavaScript statement is executed through the Document.parentWindow.execScript method to change the title of the web page to "VBA calls JavaScript".
It should be noted that when calling JavaScript using an IE instance, you also need to wait for the page to be loaded before executing JavaScript.
Conclusion
The above are two methods for VBA to execute JavaScript, using the WebBrowser control and IE instance. Both methods can implement the function of calling JavaScript in VBA, but you need to pay attention to the key point of page loading completion. I hope this article can help you solve the problem of using JavaScript in VBA.
The above is the detailed content of Two ways to execute javascript in vba. For more information, please follow other related articles on the PHP Chinese website!