首页 > 解决方案 > 使用 Excel 数据在 VBA 中创建 Word Doc 标题标签

问题描述

我正在尝试使用 VBA 将 Word 文档报告链接到 Excel 数据库。我在文档中插入了各种 ActiveX 文本框控件。我正在手动输入每个带有唯一代码(“代码”)的文本框。其他文本框控件将根据 Excel 数据库中的关联数据自动填充。匹配因子将是“代码”。

当我运行以下代码时,我收到一个

运行时错误 13“类型不匹配”

在第 16 行 ( If cell.Value...)。我在 VBA 方面没有太多经验,但我看到很多例子表明 Value 命令应该与“Range”对象相关联。谢谢您的帮助。

Private Sub CommandButton1_Click()

Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim b As Excel.Range
Dim c As Excel.Range
Dim r As Excel.Range
Dim cell As Excel.Range

'Set variables
Set exWb = objExcel.Workbooks.Open("C:\Documents\Book.xlsx")
Set b = exWb.Sheets("Sheet1").Range("B:B")
Set c = exWb.Sheets("Sheet1").Range("C:C")
Set r = exWb.Sheets("Sheet1").Rows
Set cell = exWb.Sheets("Sheet1").Range("A1:Z1000")

For Each r In c
    If cell.Value = ThisDocument.TextBox1.Value Then
        ThisDocument.TextBox2.Value = b.Value
   End If
Next r

exWb.Close
Set exWb = Nothing

End Sub

标签: excelvbams-wordactivexobject

解决方案


你可以尝试这样的事情:

Private Sub CommandButton1_Click()

    Dim objExcel As New Excel.Application
    Dim exWb As Excel.Workbook
    Dim rng As Excel.Range, m, rw As Excel.Range

    'Set variables
    Set exWb = objExcel.Workbooks.Open("C:\Documents\Book.xlsx")
    Set rng = exWb.Sheets("Sheet1").Range("A1:Z1000")

    'Here we're looking for a match in ColC...
    '  change 3 to any other column you want to match on
    m = objExcel.Match(ThisDocument.TextBox1.Value, rng.Columns(3), 0)

    If Not IsError(m) Then

        'got a match - fetch the other values from that row
        Set rw = rng.Rows(m) '<< get the matching row as a Range
        ThisDocument.TextBox2.Value = rw.Cells(1).Value 'value from colA
        ThisDocument.TextBox3.Value = rw.Cells(2).Value 'value from colB

    Else
        'no match - clear the other textboxes?
        MsgBox "No match found!"
        ThisDocument.TextBox2.Value = ""
        ThisDocument.TextBox3.Value = ""
    End If

    exWb.Close False 'no changes saved
    Set exWb = Nothing

End Sub

推荐阅读