2016-07-21 83 views
1

# 更新代碼設置驗證

Function condition(ByRef objCmb As ComboBox) 
    If objCmb.Value ="" And objCmb.Value = "g" Then 
     Call MsgBox("gg", vbOKOnly, "error") 
    End If 
End Function 

Private Sub ComboBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean) 
    condition (ComboBox1) 
End Sub 

'other codes for reference: 
Private Sub CommandButton1_Click() 
    Dim lastrow As Integer 
    lastrow = Cells(Rows.Count, "A").End(xlUp).Row 


    For i = 1 To 3 
     For j = 1 To 5 
      With Me.Controls("ComboBox" & (i - 1) * 5 + j) 
       If .Text <> "" Then 
       Cells(lastrow + i, j) = .Text 
       Else 

       Exit Sub 

       End If 

      End With 
     Next j 
    Next i 


End Sub 

我在VBA用戶面板50個組合和文本框。由於在每個組合框或文本框中設置約束條件太麻煩,我想要一個函數應用於每個組合框和文本框。

對於上面的代碼,它顯示了cant find object錯誤

如何解決?

順便說一句,如何設置功能語句的文本框? 是Function condition2(ByRef objCmb As textbox)...

+0

你在你的函數接收'objCmb'。使用它,而不是'ComboBox'。 –

+0

Ken在說什麼,是用If if objCmb.Value <>「」和objCmb.Value =「g」替換你的'If ComboBox.Value <>「」And ComboBox.Value =「g」Then'然後' –

+0

i嘗試過,仍然無法找到條件(ComboBox1)中的對象錯誤' – Monchhichi

回答

1

您收到錯誤,因爲ComboBox不是ByRef objCmb As ComboBox。調用子時不要使用括號。如果不使用函數返回值,則在調用函數時不要使用括號。如果一個函數沒有返回值,它應該是一個子類。

Sub condition(ByRef objCmb As MSForms.ComboBox) 
    If objCmb.Value <> "" And objCmb.Value = "g" Then 
     MsgBox "gg", vbOKOnly, "error" 
     objCmb.Value = "" 
    End If 
End Sub 

Private Sub ComboBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean) 
    condition ComboBox1 
End Sub 

我寫了一個函數來幫助你生成所有文本和組合框的退出事件代碼。

Sub AddCodeToCipBoard(frm As UserForm) 

    Const BaseCode = " Private Sub @Ctrl_Exit(ByVal Cancel As MSForms.ReturnBoolean)" & vbCrLf & _ 
      "  condition ComboBox1" & vbCrLf & _ 
      " End Sub" & vbCrLf & vbCrLf 

    Dim s As String 
    Dim ctrl 
    Dim clip As DataObject 
    Set clip = New DataObject 

    For Each ctrl In frm.Controls 
     If TypeName(ctrl) = "ComboBox" Or TypeName(ctrl) = "TextBox" Then 
      s = s & Replace(BaseCode, "@Ctrl", ctrl.Name) 
     End If 
    Next 

    clip.SetText s 

    clip.PutInClipboard 

End Sub 

將這個代碼模塊中並調用它像這樣:

AddCodeToCipBoard Userform1 

現在所有的退出事件代碼將被複制到Windows剪貼板。進入你的UserForms代碼模塊並粘貼新代碼。

輸出示例:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean) 
    condition ComboBox1 
End Sub 

Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean) 
    condition ComboBox1 
End Sub 

Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean) 
    condition ComboBox1 
End Sub 

Private Sub ComboBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean) 
    condition ComboBox1 
End Sub 

Private Sub TextBox4_Exit(ByVal Cancel As MSForms.ReturnBoolean) 
    condition ComboBox1 
End Sub