英文:
VBA code not accounting for the JPEG/PNG pictures in the document
问题
我的用例如下:
我想要一个宏来显示我的文档中所有图片的数量。
我已经编写了以下代码。然而,当我在一个包含一些JPEG/PNG图片的文档上运行它时,返回的计数是 0
。
请问我在这里做错了什么:
Sub countfigures()
Dim doc As Document
Set doc = ActiveDocument
Dim figureCount As Integer
figureCount = 0
Dim shape As Shape
For Each shape In doc.Shapes
' 检查形状是否是图片
If shape.Type = msoPicture Then
figureCount = figureCount + 1
End If
Next shape
MsgBox "文档中的图片数量: " & figureCount
End Sub
英文:
My use case is as follows:
I want to have a macro to display the count of all the pictures in my document.
I have put together the following code. However, when i run it on a document that has a few JPEG/PNG images, the count returned is 0
.
What am I doing wrong here please:
Sub countfigures()
Dim doc As Document
Set doc = ActiveDocument
Dim figureCount As Integer
figureCount = 0
Dim shape As shape
For Each shape In doc.Shapes
' Check if the shape is a picture
If shape.Type = msoPicture Then
figureCount = figureCount + 1
End If
Next shape
MsgBox "Number of figures in the document: " & figureCount
End Sub
答案1
得分: 3
可能 'Shape' 实际上是 'InlineShape' ... 尝试这个:
Sub countfigures()
Dim doc As Document
Set doc = ActiveDocument
Dim figureCount As Integer
figureCount = 0
Dim shape As shape
For Each shape In doc.Shapes
' 检查形状是否为图片
Debug.Print shape.Type
If shape.Type = msoPicture Then
figureCount = figureCount + 1
End If
Next shape
Dim inlineShape As inlineShape
For Each inlineShape In doc.InlineShapes
' 检查 InlineShape 是否为图片
Debug.Print inlineShape.Type
If inlineShape.Type = wdInlineShapePicture Then
figureCount = figureCount + 1
End If
Next inlineShape
MsgBox "文档中的图片数量: " & figureCount
End Sub
我包含了两个 Debug.Print
语句(一旦您的代码按您的要求正常工作,可以删除它们),这样您可以看到 Shape / InlineShape 的类型... 这里有许多这样的类型,它们对于每个 Shape 和 InlineShape 都不同,您可以在这里查看MsoShapeType和WdInlineShapeType。
英文:
Likely the 'Shape' is actually an 'InlineShape' ... try this:
Sub countfigures()
Dim doc As Document
Set doc = ActiveDocument
Dim figureCount As Integer
figureCount = 0
Dim shape As shape
For Each shape In doc.Shapes
' Check if the shape is a picture
Debug.Print shape.Type
If shape.Type = msoPicture Then
figureCount = figureCount + 1
End If
Next shape
Dim inlineShape As inlineShape
For Each inlineShape In doc.InlineShapes
' Check if the InlineShape is a picture
Debug.Print inlineShape.Type
If inlineShape.Type = wdInlineShapePicture Then
figureCount = figureCount + 1
End If
Next inlineShape
MsgBox "Number of figures in the document: " & figureCount
End Sub
... I included two Debug.Print
statements (which you can remove once your code is working just as you want it to) so you can see the type of the Shape / InlineShape ... there are many such types and they are different for each of Shape and InlineShape as you can see here MsoShapeType and here WdInlineShapeType
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论