【问题标题】:word 2007 vba can't delete all the autoshape line at onceword 2007 vba不能一次删除所有的autoshape行
【发布时间】:2015-03-12 15:37:01
【问题描述】:

我正在使用以下代码来选择和删除文档中的所有自定形线条。

它在 MSWord 2003 中运行良好。(也适用于在 2007 年打开时使用 2003 绘制的线条) 但它没有选择在 MS word 2007 中绘制的线条。

Sub line() 
Dim shp As Shape, intBoxNbr As Integer

intNbrShapes = 0
For Each shp In ActiveDocument.Shapes
If shp.Type = msoLine Then
intNbrShapes = intNbrShapes + 1
ActiveWindow.ScrollIntoView Selection.Range, True
shp.Select
Selection.Delete
'shp.Delete
'(Selection.Delete is used in MSWord 2007 and shp.Delete used in MSWord 2003)
End If
Next shp

End Sub

我发现在 MSword 2007 中绘制的线条名称为 Autoshape##,其中 2003 具有线条##。 我在文档中有其他自动形状(文本框等),所以我不能只使用“If shp.Type = msoAutoShape Then”。 请帮助如何选择和删除使用 MS Word 2007 绘制的线。

谢谢。

我现在更新了代码...它不会一次删除所有行。我需要多次运行宏才能全部删除。

Sub Macro1()
'
' Macro1 Macro
'
Dim shp As Shape, i As Integer

i = 0
For Each shp In ActiveDocument.Shapes
If shp.Type = msoAutoShape Then
i = i + 1
ActiveWindow.ScrollIntoView Selection.Range, True
shp.Select

If Selection.ShapeRange.Line.DashStyle = msoLineSolid Then
Selection.Delete
End If

'shp.Delete

End If
Next shp

End Sub

【问题讨论】:

  • 你做了什么调试?在For Each shp 语句上放置一个断点,并检查shp.Type 属性中是否存在已知的“行”。它可能不是msoLine 类型,那么显然会“失败”选择/删除这些形状。
  • 你能简单介绍一下吗?
  • 我没有 2003 或 2007 可用于测试这些条件,并且在 2010 中,形状默认名称与您描述的不同(相反,我得到“直连接器 1”等。 )。因此,您应该进行一些调试并尝试修改各种属性以查看可能的情况。
  • 当你把代码放在 cmets 中时,为什么人们不明白代码绝对难以辨认?
  • 从集合中删除项目时,总是需要向后遍历集合。

标签: vba ms-word word-2007


【解决方案1】:

当您从集合中删除项目时,必须以 reverse 顺序执行此操作。这是因为集合是索引的。考虑以下示例集合:

Item#  Name
  1      David
  2      Sergio
  3      Beatrice
  4      Eunice

如果我们确实尝试通过从 1 到 .Count 的直接迭代来删除所有项目,它将不起作用:

Sub foo()
Dim coll As New Collection
Dim i As Integer

coll.Add 1, "David"
coll.Add 2, "Sergio"
coll.Add 3, "Beatrice"
coll.Add 4, "Eunice"

For i = 1 To coll.Count
    coll.Remove (i)
Next

MsgBox coll.Count

End Sub

在第一次迭代中,i = 1,它将删除“David”,在第二次遍历中,i = 2,但由于之前删除了第 1 项,第二个索引现在是“Beatrice”,所以“Sergio”是跳过。在第三次迭代中,i = 3 但集合中不再有 3 个项目,您将收到错误消息! (下标超出范围)。如果您还没有遇到错误,那是可能的。

所以,为了避免这个问题,你需要退后一步:

For i = coll.Count to 1 Step -1
    coll.Remove(i)
Next

这意味着您必须使用索引迭代而不是For Each,因此适应您的代码,您可以尝试:

For i = ActiveDocument.Shapes.Count to 1 Step - 1
    Set shp = ActiveDocument.Shapes(i)

    If shp.Type = msoAutoShape Then

        ActiveWindow.ScrollIntoView Selection.Range, True
        shp.Select

        If Selection.ShapeRange.Line.DashStyle = msoLineSolid Then
            Selection.Delete
        End If
    End If
Next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 2012-12-06
    • 2020-03-19
    • 2019-01-16
    相关资源
    最近更新 更多