VBA中使用Selenium操作Chrome时的类型不匹配问题及PeerComparison表格表头行引用方案咨询
The "Type Mismatch" error you’re facing boils down to a core difference between how IE’s native DOM automation and Selenium ChromeDriver handle table elements. Let’s break this down and get your code working:
Why the Error Occurs
In IE’s automation model, the Rows method returns TableRow objects directly, which aligns with your variable declaration. But with Selenium ChromeDriver:
FindElementsByTag("tr")returns a collection ofWebElementobjects, notTableRowinstances.- Your variable
PeerComparisonTableHeaderRowis declared asSelenium.TableRow, which isn’t compatible with theWebElementreturned by ChromeDriver—this is exactly what triggers the type mismatch.
Solution: Adjust Variable Type & Use Selenium’s Standard API
Replace the TableRow type with WebElement (the universal element type in Selenium) and tweak your code to work with ChromeDriver’s methods:
Sub RetrievePeerComparisonHeader() Dim ChBrowser As Selenium.ChromeDriver Set ChBrowser = New Selenium.ChromeDriver Dim PeerComparisonTable As Selenium.WebElement Dim PeerComparisonTableHeaderRow As Selenium.WebElement ' Updated to WebElement ' Initialize Chrome and navigate to your target page ChBrowser.Start "chrome" ChBrowser.Get "https://www.screener.in/company/DIVISLAB/consolidated/" ' Get the second table (note: Selenium uses 0-based indexing) Set PeerComparisonTable = ChBrowser.FindElementsByTag("table")(1) ' Get the second row (adjust the index if your header sits in a different position) Set PeerComparisonTableHeaderRow = PeerComparisonTable.FindElementsByTag("tr")(1) ' Example: Verify success by printing the first header cell's text Debug.Print PeerComparisonTableHeaderRow.FindElementsByTag("th")(0).Text ' Clean up the browser session ChBrowser.Quit End Sub
Bonus: More Reliable Table Locator
Index-based locators (like (1)) are fragile—if the page structure changes, your code will break. Instead, use a CSS selector or XPath to target the Peer Comparison table directly. For example, if the table has a unique class (check the page’s HTML source), use:
' Replace with the actual class name from the page's HTML Set PeerComparisonTable = ChBrowser.FindElementByCss("table.peer-comparison")
This ensures you’re always targeting the correct table, no matter how other tables on the page are ordered.
Key Difference from IE Automation Recap
- IE’s DOM has native
Rows/Cellsmethods for tables; Selenium ChromeDriver relies on standardFindElement/FindElementscalls to locate rows and cells. - Selenium uses
WebElementas the base type for all page elements, rather than specialized types likeTableRow.
内容的提问来源于stack exchange,提问作者user19574770

