excel - 基于 MS-word VBA 宏从 Excel 工作表中读取特定列
问题描述
我想突出显示 Word 文档中 Excel 表的特定列中给出的特定单词。
我有一个工作解决方案(见下文),它从 word 文件中读取单词,但我无法使用 excel 文件中的特定列运行它来执行相同的操作。本质上,我想做以下 python 代码所做的事情(但对于 VBA):
import pandas as pd
all = pd.read_excel("list.xlsx")
docRef = all(all["MY COLUMN NAME"])
...并且应该在下面的代码中使用 docRef。我只是无法让它运行...
Sub highlightWords()
Dim sCheckDoc As String
Dim docRef As Document
Dim docCurrent As Document
Dim wrdRef As Object
sCheckDoc = "list.docx"
Set docCurrent = Selection.Document
Set docRef = Documents.Open(sCheckDoc)
docCurrent.Activate
Options.DefaultHighlightColorIndex = wdRed
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = True
.Replacement.Text = "^&"
.Forward = True
.Format = True
.MatchWholeWord = True
.MatchCase = False
.MatchWildcards = False
End With
For Each wrdRef In docRef.Words
If Asc(Left(wrdRef, 1)) > 32 Then
With Selection.Find
.Wrap = wdFindContinue
.Text = wrdRef
.Execute Replace:=wdReplaceAll
End With
End If
Next wrdRef
docRef.Close
docCurrent.Activate
End Sub
从这里修改的代码。
解决方案
为了从 Word 中控制 Excel,您应该在 Word VBA 编辑器中设置对 Excel 库的引用:工具、参考,向下滚动到 Microsoft Excel 并勾选它。
然后您需要打开 Excel,并加载工作簿
Dim XL as new Excel.Application
Dim wb as Excel.Workbook
Set wb = xl.Workbooks.open("path and name of file list.xlsx")
For Each wordref in wb.Sheets(1).Range("a1:A" & wb.Sheets(1).usedrange.rows.count)
推荐阅读
- javascript - 如何在价值中应用空间?
- c - 由于指针,乘法结果总是为零?
- javascript - 如何验证用户字符串输入不包含 sql 注入?在 Javascript 中
- angular - 如何更新 MongoDB 中的单个字段?
- java - Spring数据查询子字符串
- python-3.x - 如何从 class/def 函数加载 csv,然后如何使其读取/打印行和列?
- html - 如何对表格单元格强制使用相同的宽度?
- node.js - 为什么不能实例化一个空的 Angular 应用程序?
- laravel - 在 Laravel 中处理高频率的 API 调用
- javascript - 带有位置的粘性导航中的 CLS(累积布局移位):固定