首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用宏在Word中搜索表格以查找单元格中的特定字符串,然后在同一行中的另一个单元格上设置排版

使用宏在Word中搜索表格以查找单元格中的特定字符串,然后在同一行中的另一个单元格上设置排版
EN

Stack Overflow用户
提问于 2017-10-21 03:34:04
回答 1查看 10.5K关注 0票数 0

我有一个包含3列和未知行数的表的Word文档,我需要一个可以在第1列中搜索字符串"Sum“的宏。

如果找到完全匹配的单元格,宏必须将行中其余两个单元格的排版设置为Word中的两种不同排版,并删除单元格1中的字符串"Sum“。

该表可以包含字符串"sum“的许多实例,但它们始终位于第一列中。

我已经尝试过的代码,我为我缺乏编码技能道歉,但我只在一周内这样做,工作良好,直到"sum“的第一个实例,然后退出。

我使用的是以下代码:

代码语言:javascript
复制
Sub FindSum() 

Dim oTbl As Table  
Dim oRow As Row 

Set myRange = ActiveDocument.Content

    For Each oTbl In ActiveDocument.Tables
        For Each oRow In oTbl.Rows
            Selection.Find.Execute FindText:="Sum", ReplaceWith:=""
            If Selection.Find.Found = True Then
                Selection.MoveRight Unit:=wdCell
                Selection.Style = ActiveDocument.Styles("Titel")
                Selection.MoveRight Unit:=wdCell
                Selection.Style = ActiveDocument.Styles("Citat")
            End If
        Next
    Next 
End Sub

我希望你能帮助我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-21 11:32:33

这似乎是可行的

忽略表外的"Sum“

使用两个表进行测试

代码语言:javascript
复制
Option Explicit

Sub FindSum()

    Dim oTbl As Table
    Dim stT As Long, enT As Long
    Dim stS As Long, enS As Long

    With Selection.Find             ' the settings remain until changed
        .Text = "Sum"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
    End With

    For Each oTbl In ActiveDocument.Tables

        oTbl.Columns(1).Select                        ' not sure if this is required

        Do While Selection.Find.Execute

            stT = oTbl.Range.Start                    ' table range
            enT = oTbl.Range.End

            stS = Selection.Range.Start               ' found text range
            enS = Selection.Range.End

            If stS < stT Or enS > enT Then Exit Do    ' text found inside table ???

            Selection.Collapse wdCollapseStart
            Selection.Find.Execute Replace:=wdReplaceOne

            Selection.MoveRight Unit:=wdCell
            Selection.Style = wdStyleTitle            ' original code was invalid
            Selection.MoveRight Unit:=wdCell
            Selection.Style = wdStyleHeading3
        Loop
        Selection.Collapse wdCollapseEnd
    Next
End Sub
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46856136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档