excel - 使用 VBA 将图片插入(然后引用)到 Excel 中

标签 excel vba

我正在尝试使用 VBA 将图片插入到工作表中,稍后我可以通过名称引用它(例如删除或隐藏)。

我可以使用类似于下面的代码插入图像:

 ActiveSheet.Shapes.AddPicture Filename:="image.jpg", linktofile:=msoFalse, _
        savewithdocument:=msoCTrue, Left:=10, Top:=20, width:=100, Height:=50

但是,我正在努力将图片分配给一个形状(或其他对象),以便我可以命名它并在以后引用它。例如

Dim shp As Shape
set shp = ActiveSheet.Shapes.AddPicture Filename:="image.jpg", linktofile:=msoFalse, _
        savewithdocument:=msoCTrue, Left:=10, Top:=20, width:=100, Height:=50
shp.name = "myPicture"

... some code ...

ActiveSheet.Shapes("myPicture").Delete ' or similar code to later delete the image 

但是,我在 set shp = ... 行上遇到语法错误

我也尝试过:Dim shp As Excel.ShapeDim shp As Object 根据 SO 帖子中的评论:VBA to insert embeded picture excel但仍然出现语法错误。

我哪里错了?

最佳答案

从方法返回值时需要括号:

set shp = ActiveSheet.Shapes.AddPicture(Filename:="image.jpg", linktofile:=msoFalse, _
        savewithdocument:=msoCTrue, Left:=10, Top:=20, width:=100, Height:=50)

关于excel - 使用 VBA 将图片插入(然后引用)到 Excel 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25400943/

相关文章:

vba - 确定字符串最大允许长度 a 的通用方法

excel - 当另一个值更改时增加 vlookup 单元格引用

java - Apache POI 单元值未出现

excel - 从选定的单元格中查找表格行号

excel - 电源查询: sort by custom list

python - 是否可以在 Excel 中使用 Python 动态更改公式引用的路径?

vba - 使用范围数组的多个条件自动过滤

vba - VBA Excel 中的对象数组或集合

excel - 优化 VBA 宏

excel - 将特定单词表的内容复制到excel