【问题标题】:Delete shaded rows before save保存前删除阴影行
【发布时间】:2021-07-26 18:41:43
【问题描述】:

我有一个 Word 2013 文档,其中包含根据文档中的下拉选择对指定行进行着色的代码。

我已将其设置为在打印之前从文档中删除所有阴影行,但我希望在使用“另存为”功能之前删除所有阴影行。

打印有效的代码:

Public Sub myApp_DocumentBeforePrint(ByVal Doc As Document, Cancel As Boolean)

    Dim d1 As Document
    Set d1 = ActiveDocument
    
    Dim tbl As Table, r As Row, c As Cell, rng As Range, t As Integer
    Dim i As Integer, n As Integer
    
    'table counter
    t = 1
    
    'cycle through each table
    For Each tbl In d1.Tables
        'row counter
        n = tbl.Rows.Count
        'cycle through the rows in the selected table
        For i = 1 To n Step 1
            'compare pattern fill, select those that are shaded and delete
            If d1.Tables(t).Rows(i).Shading.Texture = wdTextureDarkDiagonalDown Then
                d1.Tables(t).Rows(i).Delete
            End If
        Next
        t = t + 1
    Next

不工作的另存为代码:

Public Sub myApp_DocumentBeforeSaveAs(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
    
    Dim d1 As Document
    Set d1 = ActiveDocument
    
    Dim tbl As Table, r As Row, c As Cell, rng As Range, t As Integer
    Dim i As Integer, n As Integer
    
    'table counter
    t = 1
    
    'cycle through each table
    For Each tbl In d1.Tables
        'row counter
        n = tbl.Rows.Count
        'cycle through the rows in the selected table
        For i = 1 To n Step 1
            'compare pattern fill, select those that are shaded and delete
            If d1.Tables(t).Rows(i).Shading.Texture = wdTextureDarkDiagonalDown Then
                d1.Tables(t).Rows(i).Delete
            End If
        Next
        t = t + 1
    Next

我没有收到任何错误代码,它只是对阴影文本没有任何作用。

【问题讨论】:

  • 首先,为了方便您自己,我将删除阴影行的代码分解为单独的Sub。然后你可以从任何地方调用 sub(在这种情况下,myApp_DocumentBeforePrintmyApp_DocumentBeforeSaveAs)。您是否验证过您的代码正在myApp_DocumentBeforeSaveAs 例程中执行?尝试一些 Debug.Print 语句和/或断点,看看您是否可以识别出不工作的行。

标签: vba ms-word


【解决方案1】:

您的代码可以正常工作,但确实会产生错误。问题出在

For i = 1 To n Step 1

代码行。要删除表中的行,您需要后退,否则当您删除一行时,剩余的行数不等于表中的行数。你的命令应该是:

For i = n to 1 Step -1 

还有一行不必要的代码

t = t + 1

这不会造成问题,但没有必要,至少根据您向我们展示的内容。

只要您纠正了第 1 步的问题,并且您确定行阴影与您指定的纹理暗对角向下一致,您的代码就会再次起作用。

【讨论】:

    猜你喜欢
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    相关资源
    最近更新 更多