【问题标题】:VBA Word: Do While LoopVBA Word:执行 While 循环
【发布时间】:2021-01-16 09:32:52
【问题描述】:

我有以下代码可以在 Word 中打开嵌入的 Excel 表格,将 A1 单元格更改为字符串“Testing”,然后关闭嵌入的 Excel。

到目前为止,这只对文档中的第一个对象运行。我希望它遍历它找到的所有对象,如下所示。请参阅“ActiveDocument.InlineShapes.Count”。我现在意识到它只在第一个 For 循环中找到 1 到 1。我已经尝试了一些不同的东西,但无法做到正确。我猜我需要一个 Do while 循环......有什么帮助解决这个问题吗?

Sub TestOpenEditandSave()

Dim oOleFormat As OLEFormat
Dim lNumShapes As Long
Dim lShapeCnt As Long
Dim xlApp As Object

'ActiveDocument.InlineShapes.Count

For lShapeCnt = 1 To 1 'ActiveDocument.InlineShapes.Count
    If ActiveDocument.InlineShapes(lShapeCnt).Type = wdInlineShapeEmbeddedOLEObject Then
        If ActiveDocument.InlineShapes(lShapeCnt).OLEFormat.ProgID = "Excel.Sheet.8" Then
            ActiveDocument.InlineShapes(lShapeCnt).OLEFormat.Edit
            Set xlApp = GetObject(, "Excel.Application")
            xlApp.Workbooks(1).Worksheets(1).Range("A1") = "Testing"

With Selection.Find
    .ClearFormatting
    .Text = "nothingMatch"
    .Execute Forward:=True
End With

        End If
    End If
Next lShapeCnt

End Sub

【问题讨论】:

  • 这看起来像 stackoverflow.com/questions/483813/… 的副本——Gary McGill 的答案在这里有效,包括停用例程,但可能是 Selection.Find 方法同样有效。该方法也适用于For Each。我遇到的主要困难是您不能单步执行 VBA 调试器中的代码,因为 VBE 似乎在某个点执行“继续”。但是你仍然可以使用断点。

标签: excel loops object ms-word embed


【解决方案1】:

如果使用 Word 中的内置集合会简单一些:

Sub FindShapes()
    Dim oInlineShape As InlineShape
    
    For Each oInLineShape In ActiveDocument.InlineShapes
        If oInlineShape.Type = wdInlineShapeEmbeddedOLEObject Then
            If oInlineShape.OLEFormat.ProgID = "Excel.Sheet.8" Then
                'Do stuff here
            End If
        End If
    Next oInlineShape
End Sub

【讨论】:

  • 您的意思是 .ProgID 副 .ProID 吗?如果 oInlineShape.Type = wdInlineShapeEmbeddedOLEObject 则出现“对象变量或未设置块变量”错误。 Next oInlineShape 线看起来也有问题。
  • 拼写错误已修复。
猜你喜欢
  • 2018-08-27
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多