我使用Word表作为图像的占位符,其中表格单元格只包含图片而不包含文本。
当将图片插入到Word表中时,插入内联形状时没有问题。图片显示在预期的单元格中。但是,使用将图片作为形状插入的“等效”代码,形状并不总是出现在预期的单元格中。到目前为止,我已经在Word 2013中看到了这个问题,32位版本。
Sub test()
Dim s As Shape
Dim x As String
Dim f As String
Dim r As Long
Dim c As Long
Dim h As Single
Dim w As Single
Dim rng As Word.Range
Dim ins As Word.InlineShape
f = "file name of a picture, .bmp .jpg etc."
Word.Application.ScreenUpdating = False
If Selection.Information(wdWithInTable) Then
' insert a picture in a table cell
r = Selection.Information(wdStartOfRangeRowNumber)
c = Selection.Information(wdStartOfRangeColumnNumber)
With Selection.Tables(1).Cell(r, c)
Set rng = .Range
rng.collapse wdCollapseStart
.Range.Text = ""
h = .height
w = .width
End With
' Works reliably
Set s = Word.Selection.InlineShapes.AddPicture(f, False, True, rng).ConvertToShape
s.height = h
s.width = w
' Not at all reliable
' Set s = Word.ActiveDocument.Shapes.AddPicture(f, False, True, 0, 0, w, h, rng)
Else
' insert a picture at the cursor
h = 100
w = 100
Set s = Word.ActiveDocument.Shapes.AddPicture(f, False, True, 0, 0, w, h)
End If
Word.Application.ScreenUpdating = True
s.WrapFormat.Type = wdWrapInline
s.Title = "Title"
s.AlternativeText = "Some metadata"
End Sub这样做的目的是在文档中的表中选择一个单元格,或者在表之外的页面上选择一个单元格。表用例的外部按照预期的方式工作,图片出现在光标位置。
要了解这个问题,请从一个新文档开始,单页,添加一个3x3表,并稍微加深行。确保提供要插入的文件,变量f。选择一个单元格,然后运行代码。当图片作为内联形状插入,然后立即转换为形状时,此操作是正确的。这发生在这一行中:
Set s = Word.Selection.InlineShapes.AddPicture(f, False, True, rng).ConvertToShape但是,首选的解决方案是从一开始就使用如下代码插入形状:
Set s = Word.ActiveDocument.Shapes.AddPicture(f, False, True, 0, 0, w, h, rng)图片出现,但通常不在预期的位置。它可以放在另一个单元格里,或者放在桌子外面的某个地方。
rng关于Shapes.AddPicture的参数是否被忽略或被破坏了?
对3x3表进行更多的实验--添加图片,然后设置每个可能的WrapFormat.Type (有8个可能的值),我看到:
WrapFormat.Type以外的每一个wdWrapInLine,只要在表行上从左到右完成,图片插入就能正常工作。WrapFormat.Type (无一例外),当行最初为空时,插入到第2或3列中的图片将显示在左边的一列。使图片变小,例如设置h = .height * 0.5和w = .width * 0.5,对布局没有影响。
非常感谢您的理解和解释。
发布于 2018-01-17 15:39:30
主要的问题似乎是图片插入错误的列。这可能是因为空表单元格的“焦点”(范围的位置)在前一个单元格中有其起点。并不是很有意义,但这就是单词的工作原理.
尝试将范围折叠到末尾,而不是从代码中提取的开始(wdCollapseEnd):
With Selection.Tables(1).Cell(r, c)
Set rng = .Range
rng.collapse wdCollapseEnd 'instead of wdCollapseStart
.Range.Text = ""
h = .height
w = .width
End With发布于 2018-01-19 11:00:25
最后,选择性地使用rng.collapse起了作用。我还没有检查这种行为在Word 2010或2016中是一样的。
对于表行中的第一个形状,rng.collapse wdCollapseEnd。
对于该表行中的所有后续形状,rng.collapse wdCollapseBegin。
我使用以下代码来计数表行中的形状:
Dim numShapes() As Integer
Dim cel As Word.cell
ReDim numShapes(1 To Selection.Tables(1).Rows.Count)
For Each cel In Selection.Tables(1).Range.Cells
If cel.Range.ShapeRange.Count <> 0 Then
numShapes(cel.RowIndex) = numShapes(cel.RowIndex) + 1
End If
Next cel支票很简单
If numShapes(r) <> 0 Then
rng.collapse wdCollapseStart
Else
rng.collapse wdCollapseEnd
End If其中r是第一个代码示例中的行号。
对合并细胞的初步实验表明还有其他问题..。
https://stackoverflow.com/questions/48286045
复制相似问题