我正在Word中创建一个vba用户表单。现在我正在开发一个功能,让用户浏览图像文件,将其加载到用户窗体中的Image控件上,并在文本框中显示文件路径(一种图像预览功能,允许用户直接更改文件)编辑文本框)。在帮助下,我已经找到了单个“浏览”按钮所需的代码,如下所示:
Private Sub btnBrowse1_Click()
Dim fd As FileDialog
Dim strPicPath1 As String
Dim vrtSelected As Variant
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
If .Show = -1 Then
For Each vrtSelected In .SelectedItems
AutoReport.txtboxPicPath1.Text = vrtSelected
strPicPath1 = vrtSelected
AutoReport.Image1.Picture = LoadPicture(strPicPath1)
Next vrtSelected
Else: Exit Sub
End If
End With
End Sub
然而,由于我有大约8个浏览按钮,我想通过编写一个程序来“概括”这个过程,这样我就可以调用它而不是写相同的结构8次,如下所示:
Sub FormLoadPicture(TxtboxToFill As TextBox, ImageBox As Image, objForm As Object)
Dim fd As FileDialog
Dim vrtSelected As Variant
Dim PicPath As String
Dim i As Long
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
If .Show = -1 Then
For Each vrtSelected In .SelectedItems
objForm.TxtboxToFill.Text = vrtSelected
PicPath = vrtSelected
objForm.ImageBox.Picture = LoadPicture(PicPath)
Next vrtSelected
Else: Exit Sub
End If
End With
End If
Next i
End Sub
当我调用它时(即FormLoadPicture(txtboxPicPath2,Image2,me)),它给了我一个“语法错误”。我怀疑我正在编写用于引用表单控件的代码错误但我不知道应该是什么右。
答案 0 :(得分:0)
欢迎来到这个论坛 我在这里看到几点:
1)。
是的,这很令人困惑,但像Textbox
和Image
这样的类似似乎是指工作表上使用的ActiveX控件类型。 userforms上的控件有不同的类型,你必须在这里使用它:
Sub FormLoadPicture(TxtboxToFill As MSForms.TextBox, _
ImageBox As MSForms.Image, objForm As MSForms.UserForm)
2。)
如果您不使用AllowMultiSelect
,则不必使用循环,只需使用.SelectedItems(1)
3。)
您的参数是对象的引用,您可以(仅)使用它们,而不是用户形式的属性
这意味着ImageBox.Picture = LoadPicture(PicPath)
而不是objForm.ImageBox.Picture = LoadPicture(PicPath)
4)。
当您调用sub时,您可能不会使用括号,如FormLoadPicture(txtboxPicPath2,Image2,me)
中所示
如果只有一个参数,但是具有不同的含义(将参数放在括号中强制按值传递),这可以(通常可以看到)。
(只有赋值右侧的函数调用才会放入VBA的括号中。)
Private Sub CommandButton1_Click()
FormLoadPicture Me.TextBox1, Me.Image1, Me
End Sub
Sub FormLoadPicture(TxtboxToFill As MSForms.TextBox, _
ImageBox As MSForms.Image, objForm As MSForms.UserForm)
Dim fd As FileDialog
Dim PicPath As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
If .Show = -1 Then
PicPath = .SelectedItems(1)
TxtboxToFill.Text = PicPath
ImageBox.Picture = LoadPicture(PicPath)
Else: Exit Sub
End If
End With
End Sub