首页 > 解决方案 > 基于 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

这里修改的代码。

标签: excelvbams-word

解决方案


为了从 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)

推荐阅读