2015-06-25 25 views
0

我在Sheet1中獲得了3個ActiveX組合框。 我在This Workbook中使用了一些代碼來填充第一個組合框列表。然後我創建了一些函數來獲取下一組值爲cascading值的組合框。下面是函數:類型不匹配創建ActiveX控件下拉列表時VBA中的錯誤

Function CascadeChild(TargetChild As OLEObject) 
     Dim Myconnection As Connection 
     Dim cmd As ADODB.Command 
     Dim Myrecordset As Recordset 
     Dim Myworkbook As String 
     Dim strSQL As String 

Set Myconnection = New ADODB.Connection 
Set cmd = New ADODB.Command 
Set Myrecordset = New ADODB.Recordset 

'Identify the workbook you are referencing 
    Myworkbook = Application.ThisWorkbook.FullName 




'Open connection to the workbook 
    Myconnection.Open "--" 

Select Case TargetChild.Name 

    Case Is = "Directorate" 

     strSQL = "Select Distinct Directorate AS [TgtField] from DBTable Where Division = '" & Sheet1.Division.Value & "' or 'All' = '" & Sheet1.Division.Value & "'" 
    Case Is = "Area" 
     strSQL = "Select Distinct Area AS [TgtField] from DBTable Where (Division = '" & Sheet1.Division.Value & "' or 'All' = '" & Sheet1.Division.Value & "') AND (Directorate = '" & Sheet1.Directorate.Value & "' or 'All' = '" & Sheet1.Directorate.Value & "')" 
End Select 

'Load the Query into a Recordset 
    Myrecordset.Open strSQL, Myconnection, adOpenStatic 


'Fill the target child listbox 
    With TargetChild.Object 
     .Clear 
     Do 
     .AddItem Myrecordset![TgtField] 
     Myrecordset.MoveNext 
     Loop Until Myrecordset.EOF 
     .Value = .List(0) '<<Automatically selects the first value in the ListBox 
    End With 



'Clean up 
    Myconnection.Close 
    Set Myrecordset = Nothing 
    Set Myconnection = Nothing 

End Function 

然後我就在VBA編寫一些代碼在Sheet1:

Private Sub Division_Change() 
Call CascadeChild(ActiveSheet.OLEObjects(Sheet1.Directorate.Name)) 
End Sub 
Private Sub Directorate_Change() 
Call CascadeChild(ActiveSheet.OLEObjects(Sheet1.Area.Name)) 
End Sub 

第一個組合框中賦予值,然後當我從ActiveX控件選擇值,誤差MSG與

填充

運行時錯誤,類型不匹配

的ERRO R 2與調試模式在這裏.AddItem Myrecordset![TgtField] 任何幫助

+0

請給一些更多的上下文。什麼是TargetChild?你使用什麼類型的ActiveX控件?哪一行你會得到錯誤? – nhee

+0

當然我會更新查詢更多..謝謝 – user3583912

+0

我更新了我的問題上面我希望你現在能理解。謝謝 – user3583912

回答

2

來嘗試

.AddItem Myrecordset.Fields(0).Value 
+0

嗨CharlieOscarDeltaEcho,謝謝你的回答,我一整天都在爲此苦苦掙扎。我現在在組合框中有值。再次感謝。 – user3583912