如何从活动文档目录添加文件

时间:2014-04-24 09:21:49

标签: vba ms-word word-vba

我有一个文档,每当我需要在文档中插入特定项目时,就会从VBA脚本创建模板页面,这样可以节省大量时间,其中包括图像。我有一个工作基础,它插入图像和文本包装在我想要的地方,但文件路径是绝对的。我希望文件路径指定图像文件与活动文档位于同一目录中,这样如果我将目录移动到其他位置,该宏将不会被破坏。

这个问题有点超出了我的vba技能,我已经解决了我应该使用ActiveDocument.Path命令,但我不知道如何。我感谢您的帮助。谢谢

到目前为止,我的代码如下:

Sub Inser_Wrapped_Image()
    Dim shp As Shape
    Set shp = ActiveDocument.Shapes.AddPicture( _
        FileName:="C:\Users\Edoardo\Documents\My Work\PhD\SkyDrive\Tutoring\Houria\Image Replacement.jpg", _
        SaveWithDocument:=True, _
        Anchor:=Selection.Range)
    With shp
        .WrapFormat.Type = wdSquare
        .Left = 246
        .Top = 50
        .Width = 250
        .Height = 188
    End With
End Sub

我尝试过如下编写,但是文字会冻结几秒钟然后什么都不做:

Sub Insert_image()
    Dim shp As Shape
    Set shp = ActiveDocument.Shapes.AddPicture( _
        FileName:=ActiveDocument.Path & "\Image.jpg", _
        SaveWithDocument:=True, _
        Anchor:=Selection.Range)
End Sub

1 个答案:

答案 0 :(得分:1)

试试这个:

Sub Inser_Wrapped_Image()
    Dim shp As Shape
    Dim imgpath As String

    imgpath = ThisDocument.Path
    imgpath = imgpath & "\" & "Image Replacement.jpg"

    Set shp = ThisDocument.Shapes.AddPicture( _
        FileName:=imgpath, SaveWithDocument:=True, _
        Anchor:=Selection.Range)
    With shp
        .WrapFormat.Type = wdWrapSquare
        .Left = 246
        .Top = 50
        .Width = 250
        .Height = 188
    End With
End Sub

我使用ThisDocument将图片显式加载到包含宏的文档中 如果你想坚持ActiveDocument,那么它会双向思考。

相关问题