1.ALT+F11打开VBE编辑器,新建一个模块1,输入如下代码:
Sub picxz() '以插入图片文件原名称作为图形名称,单元格大小为基准,依次先行方向再列方向插入,即先A1,A2....再B1,B2....依次类推
Dim picname As Variant, p As Shape, pname As String, stly, p1 As Shape, pnamewr As String, x As Byte, x1 As Byte, itop, ileft, iheight, iwidth, l As Long, h As Long
Const hs As Long = 65536 '每列所能插入图片的最大个数
stly = vbQuestion & vbYesNo
l = -Int(-Sheets("图库").Shapes.Count / hs) '列号
h = Sheets("图库").Shapes.Count - (l - 1) * hs '行号
picname = Application.GetOpenFilename(FileFilter:="图片文件 (*.jpg; *.gif;*.bmp),*.jpg; *.gif;*.bmp,所有文件(*.*),*.*", _
Title:="图片选择", MultiSelect:=False)
If picname <> False Then
pname = Split(Dir(picname), ".", 2)(0) '取图片文件原名称
pnamewr = pname
itop = Sheets("图库").Cells(h, l).Top '确定坐标
ileft = Sheets("图库").Cells(h, l).Left
iheight = Sheets("图库").Cells(h, l).Height '确定大小
iwidth = Sheets("图库").Cells(h, l).Width
For Each p In Sheets("图库").Shapes
If p.Name = pname Then
x = MsgBox("发现你的图库中已经存在同名图片,请确定是否为新图片?", stly, "图片重名,警告!")
If x = 7 Then
Exit Sub
Else
x1 = MsgBox("您确定需要替换名为:《" & pname & "》的图片吗?", stly, "图片替换,警告!")
If x1 = 6 Then
itop = Sheets("图库").Shapes(pname).Top
ileft = Sheets("图库").Shapes(pname).Left
iheight = Sheets("图库").Shapes(pname).Height
iwidth = Sheets("图库").Shapes(pname).Width
Sheets("图库").Shapes(pname).Delete
Else
chongshu:
If pnamewr = "" Then
pnamewr = InputBox("您尚未对图片命名,需要正确命名,方能插入此图片!", "图片命名")
Else
pnamewr = InputBox("您的图库已经存在以《" & pnamewr & "》为名称的图片,需要重新命名,方能插入此图片!", "图片命名")
End If
If pnamewr = "" Or pnamewr = pname Then
jinggao:
MsgBox "警告!输入为空或为同名!请继续输入", vbExclamation, "图片命名警告!"
GoTo chongshu
End If
For Each p1 In Sheets("图库").Shapes
If p1.Name = pnamewr Then GoTo jinggao
Next
End If
End If
End If
Next
ActiveSheet.Pictures.Insert(picname).Select
With Selection.ShapeRange
.Name = pnamewr
.LockAspectRatio = msoFalse
.Top = itop
.Left = ileft
.Height = iheight
.Width = iwidth
.Rotation = 0#
End With
End If
End Sub
⑵ vba 怎么自动插入多个文件夹中的图片
1.打开Excel文件,录入数据。
⑶ VBA 窗体控件 图片控件
picturebox1.picture=loadpicture("图片地址")