我对这个问题感到非常疯狂,请帮助我。
我制作了一个 shell 脚本,它在文本文件中写入存储在文件夹中的一些图像的路径。然后我使用 excel 代码读取每个路径并将其写入 excel 单元格。
然后我制作了一个应该采用该路径并使用它来插入图片的代码。我试过 Pictures.insert(path) 和 shapes.addpictures "path",但每次都遇到同样的问题,图片无法加载。
奇怪的是,如果我之前手动插入图片然后删除,代码会完美加载图片。但如果是第一次,那就没有了。
我使用的路径如下所示:“/Users/theodorebedos/Documents/code_tilly/new_pict_tilly/IMG_9040.jpg”
我正在使用Mac,也许这很重要?
Private Sub Convert_Img()
Dim myPict As Picture
Dim PictureLoc As String
Dim EndPictRow, i As Integer
Dim StartPath As String
If Worksheets("Main").Cells(3, 1).Value <> "" Then
EndPictRow = Worksheets("Main").Range("A2").End(xlDown).Row
For i = 3 To EndPictRow
PictureLoc = Worksheets("Main").Cells(i, 1).Value
Worksheets("Main").Cells(i, 1).ClearContents
Worksheets("Main").Cells(i, 1).ColumnWidth = 30
Worksheets("Main").Cells(i, 1).RowHeight = 150
ActiveSheet.Shapes.AddPicture PictureLoc, False, True, Worksheets("Main").Cells(i, 1).Left, Worksheets("Main").Cells(i, 1).Top, Worksheets("Main").Cells(i, 1).Width, Worksheets("Main").Cells(i, 1).Height
Next i
End If
End Sub
编辑:
当我使用“Pictures.insert”或“shapes.addpicture path, true, true”时,我在 VBA 中没有错误消息,但我在 excel 中而不是我的图片中有一个空白图像,其中包含如下错误消息:
image
如果我使用“shapes.addpicture path, FALSE, true”,那么我会收到这样的错误消息,但根本没有加载图像:image 2
然后是这样的错误1004:
image3
如果我执行该过程以获得图像 1,然后我保存文档,重新打开它,我将直接获得:image 4
谢谢你的帮助。将不胜感激。
最佳答案
我简化了您的代码,因此可以看到它在做什么。请注意,我避免从刚刚设置或显而易见的单元格属性中读取值。
当然,您试图实现的是只输入一次值。这是一个很好的做法,但从工作表中读取属性很慢。更快的方法——更少的代码量和更好的可读性——是在顶部声明一个常量并在代码中使用该名称。
所以你最终得到了这段代码。
Private Sub Convert_Img()
Const ClmWidth As Single = 30
Const RowHight As Single = 150
Dim EndPictRow As Long, R As Long
' sorry, I recommend i for arrays and R for rows (C for columns)
With Worksheets("Main")
' End(xlDown) will find the first blank cell below the base cell.
' There might be more filled cells further down.
' End(xlUp) will find the first used cell above the base cell
' disregarding more blanks above that one.
EndPictRow = .Cells(.Rows.Count, "A").End(xlUp).Row
' no need to set the column width multiple times in the loop
.Columns(1).ColumnWidth = ClmWidth
' this loop will never run if R < EndPicRow
For R = 3 To EndPictRow
With .Cells(R, 1)
.RowHeight = RowHight
' this will work only once:-
.Worksheet.Shapes.AddPicture CStr(.Value), False, True, 0, .Top, ClmWidth, RowHight
End With
Next R
End With
End Sub
它只工作一次的原因变得非常明显。新图片的源路径来自单元格的
Value
.当然,一旦您在单元格中插入图片(图像),该值就不能再成为路径(字符串)。如果您再次运行该代码,它将失败。但是,如果这是您的需要,应该可以从定义单元格中图片的公式中提取路径。鉴于图片本身不存在于该位置,公式应保存路径或对工作簿背景数据中某个位置的引用,具体取决于它的加载方式。
关于excel - 无法使用 VBA 在 Excel 中插入图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60793617/