首页 > 解决方案 > VBA:excel数据到html表条目

问题描述

我正在编写一些 VBA 代码,目的是从我的 Excel 工作表中获取信息并输入网页中的表格。到目前为止,我已经设法让 Internet Explorer 打开,我的工作表被引用。我试图向其中插入数据的表的代码如下所示:

    <td valign="top" align="right" class="label">
        Problem <br>Description
        <font color="red" size="+1">*</font>
    </td>
    <td class="data" colspan="5">
        <textarea name="eventVO.problemComments" cols="150" rows="3" id="eventVO.problemComments" class="data" title="Problem <br>Description">fffff</textarea>
    </td>

</tr>

当我尝试使用以下代码修改“textarea”时收到无效参数:

Sub FillInternetForm()

Dim wb As Workbook
Dim ws As Worksheet

Set wb = Workbooks("aqe.xlsm")
Set ws = wb.Worksheets("sheet1")
'open xlm for reference

Dim IE As Object
Set IE = New InternetExplorerMedium
'create new instance of IE
'With IE
IE.Navigate "url"
'go to all quality events
IE.Visible = True

'Dim Document As HTMLDocument
'Set Document = .Document
Set elems = IE.Document.getElementsByTagName("tr")
'For Each e In elems

lookFor = "<td>"

For x = 2 To 10

If elems.innerText Like "eventVO.problemComments" Then
'finding correct <tr>

    elems.getElementsByTagName("textarea").Value = ws.Cells("x, 9")
    'enter problem description
    'For x = 2 To 10

    'get full html inside the <tr><tr>
    'fullHTML = e.innerHTML

End If

if elems.getElementsByTagName 后出现运行时错误 438。如何克服此错误并将问题描述文本区域的值设置为单元格值?

标签: vbaexcelhtml-table

解决方案


你有一个 id 所以使用它。理论上它应该是唯一的。

IE.Document.getElementById("eventVO.problemComments")

其他:

更多 HTML 和/或 URL 将有助于进一步提供建议。

但是,如果您打算循环遍历带有textarea标签的元素集合,那么根据@TimWilliams 评论,您将遍历集合并按索引访问各个项目。但是,您需要修复分配语法, ws.Cells("x, 9")这不起作用,我可能会使用 CSS 选择器nodeList来遍历 a。


CSS 选择器:

.document.querySelectorAll("textarea[name='eventVO.problemComments']")

这表示选择具有标签名称且textarea属性name值为 的元素'eventVO.problemComments'

对于返回的循环,nodeList您将具有以下内容:

Dim x As Long, aNodeList As Object
Set aNodeList =IE.document.querySelectorAll("textarea[name='eventVO.problemComments']")

For x = 0 To aNodeList.Length -1

    aNodeList.Item(x) = ws.Cells(x+2,9)  '<Note how there is no "" inside the ()
   ' aNodeList(x) '<==potentially variation in syntax
Next x

您可能还可以循环测试名称的 textarea 类对象的集合:

Dim a As Object, b As Object
Set a = ie.document.getElementsByTagName("textarea") '<=collection

For Each b In a
    'On Error Resume Next ''<=This may potentially be needed if not all have a name attribute
    If InStr(1, b.getAttribute("name").innerText, "eventVO.problemComments") > 0 Then   'You might be able to just say If b.Name = eventVO.problemComments
     'Do something with the matched element
    End If
    'On Error GoTo 0
Next b

推荐阅读