在工作过程中需要向Excel单元格中批注中插入图片,VBA代码记录如下:
'insert photoSub pictopz()Dim cell As Range, fd, t, w As Byte, h As Byte, fso, picsSet fso = CreateObject("scripting.filesystemobject")Selection.ClearCommentsIf Selection(1) = "" Then MsgBox "不能选择空白区。", 64, "提示": Exit SubOn Error GoTo errSet fd = Application.FileDialog(msoFileDialogFolderPicker) '允许用户选择一个文件夹If fd.Show = -1 Thent = fd.SelectedItems(1) '选择之后就记录这个文件夹名称ElseExit Sub '否则就退出程序End Ifw = Application.InputBox("您希望插入的图片显示多宽?" & Chr(10) & "Excel默认宽度为3.39,你可以输入1-15之间的数据。" & Chr(10) & "小于1时当做1计算。", "确认宽度", 3.39, , , , , 2)h = Application.InputBox("您希望插入的图片显示多高?" & Chr(10) & "Excel默认高度为2.09,你可以输入1-15之间的数据。" & Chr(10) & "小于1时当做1计算。", "确认高度", 2.09, , , , , 2)If w < 1 Or h < 1 Then w = 3.39: h = 2.09If w > 15 Or h > 15 Then MsgBox "原则上你的图片可以显示这么大," & Chr(10) & "不过有必要吗?请重新输入1-15之间的数", 64, "提示": Exit SubFor Each cell In Selectionpics = t & "\" & cell.Text & ".jpg"If fso.fileexists(pics) ThenWith cell.AddComment.Visible = True.Text Text:="".Shape.Select TrueWith Selection.ShapeRange.Fill.UserPicture pics.ScaleWidth w / 3, msoFalse, msoScaleFromTopLeft.ScaleHeight h / 2.09, msoFalse, msoScaleFromTopLeftEnd Withcell.Offset(1, 0).Select.Visible = FalseEnd WithEnd IfNextExit Suberr:ActiveCell.ClearCommentsMsgBox "未找到同名的JPG图片!", 64, "提示"End Sub
使用方法:
选取EXCEL中需要插入图片的货品编码,执行插入图片宏代码,将会让你打开放图片的文件夹,选中文件夹即可。
注意事项:需要插入的图片需要用对应的货品编码命名,当前图片格式选用jpg.
