所以我在这里和互联网上的各个网站进行了广泛的搜索,但我很难找到答案.我也不是VBA最精明的用户.
基本上,我需要的是:点击一下按钮,弹出"插入图像"对话框,用户选择一个图像文件,图像应插入到单元格B2中.理想情况下,我想调整此图像的大小,使其不超过X,并且不高于Y.
这是我的代码到目前为止(它给我一个'运行时错误424'并指向TextBox1.Value行).任何建议/改进总是非常感谢!
Sub ChangeImage()
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.ButtonName = "Submit"
.Title = "Select an image file"
.Filters.Clear
.Filters.Add "JPG", "*.JPG"
.Filters.Add "JPEG File Interchange Format", "*.JPEG"
.Filters.Add "Graphics Interchange Format", "*.GIF"
.Filters.Add "Portable Network Graphics", "*.PNG"
.Filters.Add "Tag Image File Format", "*.TIFF"
.Filters.Add "All Pictures", "*.*"
If .Show = -1 Then
TextBox1.Value = .SelectedItems(1)
Image1.PictureSizeMode = fmPictureSizeModeZoom
Image1.Picture = LoadPicture(.SelectedItems(1))
Else
MsgBox ("Cancelled.")
End If
End With
End Sub
Run Code Online (Sandbox Code Playgroud)
谢谢!
-一个
这是使用不同类型的插入执行此操作的一种方法.示例还说明了如何定位和缩放图像.
Sub ChangeImage()
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.ButtonName = "Submit"
.Title = "Select an image file"
.Filters.Clear
.Filters.Add "JPG", "*.JPG"
.Filters.Add "JPEG File Interchange Format", "*.JPEG"
.Filters.Add "Graphics Interchange Format", "*.GIF"
.Filters.Add "Portable Network Graphics", "*.PNG"
.Filters.Add "Tag Image File Format", "*.TIFF"
.Filters.Add "All Pictures", "*.*"
If .Show = -1 Then
Dim img As Object
Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))
'Scale image size
'img.ShapeRange.ScaleWidth 0.75, msoFalse, msoScaleFromTopLeft
'img.ShapeRange.ScaleHeight 0.75, msoFalse, msoScaleFromTopLeft
'Position Image
img.Left = 50
img.Top = 150
'Set image sizes in points (72 point per inch)
img.Width = 150
img.Height = 150
Else
MsgBox ("Cancelled.")
End If
End With
End Sub
Run Code Online (Sandbox Code Playgroud)