vba Excel VBA从列中的图像名称插入图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15588995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 20:12:33  来源:igfitidea点击:

Excel VBA Insert Images From Image Name in Column

imageexcelexcel-vbavba

提问by Reg

Been reading a lot if different threads about inserting images and re-sizing them but cannot find one that does exactly what I want it to do.

阅读了很多关于插入图像和重新调整图像大小的不同线程,但找不到完全符合我想要它做的事情。

So say I have a spreadsheet with 2 rows. Column A which is the image column and Column B which is the Image Name.

所以说我有一个有 2 行的电子表格。A 列是图像列,B 列是图像名称。

I want to have a script that will run through each value in column B, insert the image that matches that name into the same Row on Column A, Resize it to fit the size of the cell which is 150 high by 18 wide, then move on to the next row and repeat through the spreadsheet.

我想要一个脚本来运行 B 列中的每个值,将与该名称匹配的图像插入 A 列上的同一行,调整其大小以适合 150 高 x 18 宽的单元格的大小,然后移动到下一行并在电子表格中重复。

回答by David Zemens

Here is a sample that will iterate over a range of cells (B1:B100) which you can modify, and uses the filename from the cell one column to the left (so, from Column A), and sizes the image to fit within cell in column B.

这是一个示例,它将迭代您可以修改的一系列单元格 (B1:B100),并使用单元格左侧一列(因此,来自 A 列)的文件名,并调整图像大小以适合单元格在 B 栏中。

Sub InsertPic()
Dim pic As String 'file path of pic
Dim myPicture As Picture 'embedded pic
Dim rng As Range 'range over which we will iterate
Dim cl As Range 'iterator

Set rng = Range("B7:B7")
For Each cl In rng
    pic = cl.Offset(0, -1)

        Set myPicture = ActiveSheet.Pictures.Insert(pic)
        '
        With myPicture
            .ShapeRange.LockAspectRatio = msoFalse
            .Width = cl.Width
            .Height = cl.Height
            .Top = Rows(cl.Row).Top
            .Left = Columns(cl.Column).Left
        End With
        '

Next

End Sub

There is no error-handling in this code to account for invalid filenames, you will probably want to add that.

此代码中没有错误处理来解释无效的文件名,您可能需要添加它。