在Visual-VBA中将图像作为形状插入

时间:2013-05-09 16:37:59

标签: vba visio

我希望能够使用VBA将图像作为Visio中的形状导入。我试图使用以下内容插入图像,但它不起作用... myShape.Import(imagePath)

但是,myPage.Import(imagePath)工作正常并将图像放在页面的中心,但我无法将其作为形状进行操作。我试过在网上搜索,但似乎找不到使用VBA的方法。

1 个答案:

答案 0 :(得分:1)

只需扩展@tim和@mike评论,这是一个将导入部分包装成函数的快速片段

Sub TryAddImage()
Dim vPag As Visio.Page
Set vPag = ActivePage
Dim shpImg As Visio.Shape

Set shpImg = AddImageShape(vPag, "C:\MyImage.jpg")

If Not shpImg Is Nothing Then
    'Do something to your new shape
    shpImg.CellsU("Width").FormulaU = "=Height*0.5"
End If
End Sub


Private Function AddImageShape(ByRef vPag As Visio.Page, fileName As String) As Visio.Shape
Dim shpNew As Visio.Shape
If Not vPag Is Nothing Then
    Dim UndoScopeID1 As Long
    UndoScopeID1 = Application.BeginUndoScope("Insert image shape")

    On Error Resume Next:
    Set shpNew = vPag.Import(fileName)

    If Not shpNew Is Nothing Then
        Application.EndUndoScope UndoScopeID1, True
    Else
        Application.EndUndoScope UndoScopeID1, False
    End If
End If
Set AddImageShape = shpNew
End Function

基本上,该函数尝试从import method返回一个形状。如果该方法通过不存在的路径或未安装的相应图像过滤器创建错误,则该函数返回“Nothing”,然后您可以在调用代码中对此进行测试。