簡體   English   中英

VBA將參數傳遞給userform

[英]VBA pass argument to userform

我有一個用戶表單,希望將其傳遞給它。 我嘗試了幾種不同的方法來執行此操作,但似乎沒有用。

這是子代碼:

 Option Explicit Sub Additional_Comments_Normal() Dim MSG1 As Integer Dim msg As String Dim act As Range On Error GoTo ErrHandler 'Calls userform MSG1 = MsgBox("Would you like to add comments", vbYesNo, "Add comments") If MSG1 = vbYes Then With AddComments On Error Resume Next Set act = Application.InputBox(Prompt:="Please choose files you wish to add comments to", Type:=8) If act Is Nothing Then Exit Sub End If Application.ScreenUpdating = True .Show End With Else Exit Sub End If ErrHandler: If Err.Number <> 0 Then msg = "Error # " & Str(Err.Number) & " was generated by " _ & Err.Source & Chr(13) & Err.Description MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext End If End Sub 

用戶表單代碼在這里:

 Public act As Range Private Sub CommandButton1_Click() Dim ctl As Control Dim rng As Range Dim MSG2 As Integer Dim sfile As String If act.Column > 1 Then MsgBox ("Please choose File name from Column 1") Exit Sub End If If act.Row < 4 Then MsgBox ("Please choose a valid file") Exit Sub End If If Me.TxtComment.Value = "" Then MsgBox "Please add comments", vbExclamation, "Additional Comments" Me.TxtComment.SetFocus Exit Sub End If If Me.TxtName.Value = "" Then MsgBox "Please add your name", vbExclamation, "Additional Comments" Me.TxtName.SetFocus Exit Sub End If MSG1 = MsgBox("Add Comments ?", vbYesNo, "Add comments") If MSG1 = vbNo Then End If If MSG1 = vbYes Then act.Offset(0, 16).Value = act.Offset(0, 16).Text & " " & Me.TxtComment.Value act.Offset(0, 17).Value = act.Offset(0, 17).Text & " " & Me.TxtName.Value For Each ctl In Me.Controls If TypeName(ctl) = "TextBox" Then ctl.Value = "" End If Next ctl AddComments.Hide Application.DisplayAlerts = False ActiveWorkbook.Save Application.DisplayAlerts = True End If End Sub Private Sub CommandButton2_Click() End Sub Private Sub CommandButton3_Click() Unload Me End Sub Private Sub UserForm_Click() End Sub 

然后,我收到有關該行為未定義變量的錯誤。

誰能為此提供更好的流程?

您已在代碼頂部設置了Option Explicit 這意味着需要定義所有變量(這被認為是良好的編程習慣)。 因此,您有兩種方法可以解決此問題:

(1)從您的代碼中刪除Option Explicit行,或者

(2)使用Dim命令定義所有變量。 在這種情況下,您必須在表單上的Sub CommandButton1_Click添加Dim act as Range

如果您想將變量傳遞給另一個子,則可以使用該變量調用該子,如下所示:

Call Additional_Comments_Normal(act)

子標頭需要像這樣更改:

Sub Additional_Comments_Normal(ByVal act as Range)

'(your code)'

End Sub

如果“將變量傳遞給另一個子項”太麻煩了,那么您也可以將范圍保存在文件中的某處,如下所示:

SomeHiddenSheet.Range("A1").Value2 = act

在另一個子目錄中,您可以再次啟動操作:

act = SomeHiddenSheet.Range("A1").Value2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM