excel - 使用 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
解决方案
你可以尝试这样的事情:
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
推荐阅读
- stripe-payments - 当你有密钥时如何获得条带公钥?
- python - 无法从 Linux 虚拟网络接口发送/接收单播以太网数据包
- matlab - 从下标参考中查找每个维度中的所有索引位置
- r - mlr3 中的 randomForest 在计算特征重要性分数时抛出错误
- reactjs - 如何从数据网格中获取隐藏列
- laravel - Laravel“队列:修剪批次”未定义
- c# - 我在上下文中进行了配置,但它创建了新的列 ef 核心迁移?
- javascript - Chart.js 第二个图表不会加载
- flutter - 空格在 url_launcher mailto 方案中转换为 + 扑
- ios - NSInternalInconsistencyException 导致崩溃,即使它被包裹在 do-try-catch 中