【问题标题】:How to add picture in Word document and adjust its size and position?如何在Word文档中添加图片并调整其大小和位置?
【发布时间】:2014-09-18 06:11:35
【问题描述】:

设置是:带有一些用户名和文件名的 Excel 表(因为文件是某个目录中的照片)。目的是通过将模板中的变量更改为真实用户名并向其添加照片,根据所选行的数据创建 Word 文档。问题在于该照片的定位和设置属性。由于Selection.Shapes.AddPicture 方法返回错误(运行时错误'438':对象不支持此属性或方法),我使用了Selection.InlineShapes.AddPicture 方法。所以,以下是我的实际代码,我希望有人能帮助我。提前致谢!

Option Explicit

Sub CreateDocs()

    Const wdReplaceAll = 2

    Dim user_name As String, user_surname As String, user_patronymic As String
    Dim user_type As String, user_type_num As Integer, user_country As String
    Dim user_pic As String, pic As Object
    Dim wrd As Object, doc As Object
    Dim length As Integer
    Dim ind As Integer

    Dim pict As Object

    ind = ActiveCell.Row

    With Sheets("SHEET_NAME")
        user_name = .Cells(ind, 4)
        user_surname = .Cells(ind, 3)
        user_type = .Cells(ind, 22)
        user_pic = .Cells(ind, 25)
    End With

    Set wrd = CreateObject("Word.Application")
    wrd.Visible = True

    Set doc = wrd.Documents.Add(ThisWorkbook.Path & "\SUBPATH\TMPL.dotx")

    Set pic = wrd.Selection.InlineShapes.AddPicture( _
        Filename:=ThisWorkbook.Path & "\SUBPATH\" & user_pic, _
        LinkToFile:=False, _
        SaveWithDocument:=True _
    )
    pic.ConvertToShape
      ' THE NEXT 4 CODE LINES DOESN'T WORK AT ALL
      ' I have the same error here:
      ' Run-time error '438': Object doesn't support this property or method
    pic.LockAspectRatio = msoTrue
    pic.Left = 197
    pic.Top = 191
    pic.Width = 179

    With wrd.Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "%user_name%"
        .Replacement.Text = user_name
        .Execute Replace:=wdReplaceAll
        .Text = "%user_surname%"
        .Replacement.Text = user_surname
        .Execute Replace:=wdReplaceAll
        .Text = "%user_type%"
        .Replacement.Text = user_type
        .Execute Replace:=wdReplaceAll
    End With

    doc.SaveAs ThisWorkbook.Path & "\SUBPATH\" & user_name & ".docx"

    doc.Close False
    Set doc = Nothing

    wrd.Quit False
    Set wrd = Nothing

End Sub

【问题讨论】:

    标签: image vba excel ms-word


    【解决方案1】:

    尝试创建另一个变量(我们称之为 picShape)并将其设置为 ConverttoShape 的结果。所以,

    Dim picShape As Object
    .....
    Set picShape = pic.ConvertToShape
    picShape.LockAspectRatio = msoTrue
    picShape.Left = 197
    picShape.Top = 191
    picShape.Width = 179
    

    我希望我能对此提供更全面的解释,但我很少使用后期绑定。从 Local 窗口的外观来看,pic.ConvertToShape 似乎并没有真正改变 pic 的底层类型(尽管它确实将实际图片从 inlineshape 更改为 shape)。因此,要么您此时无法更改类型,要么此方法不会以您可能期望的方式影响应用它的变量。

    【讨论】:

    • 非常感谢!似乎我现在理解了 VBA 中对象的机制:如果我在某个变量中更改对象的类型,它将变得无法进一步访问。这就是为什么即使在这种意想不到的情况下也会有如此多的对象返回。
    猜你喜欢
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2015-06-02
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多