创建ActiveX控件下拉列表时,VBA中的类型不匹配错误

时间:2015-06-25 12:03:06

标签: vba excel-vba excel-2010 excel

我的sheet1中有3个ActiveX组合框。 我在cascading中使用了一些代码来填充第一个组合框列表。然后我创建了一些函数来获取 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 值的下一组组合框。以下是功能:

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

然后我在VBA中的Sheet1中编写了一些代码:

.AddItem Myrecordset![TgtField]

第一个组合框给出值,然后当我从ActiveX控件中选择值时,错误MSG用

填充
  

运行时错误,类型不匹配

此处调试模式出现错误{{1}} 任何帮助

1 个答案:

答案 0 :(得分:2)

尝试

.AddItem Myrecordset.Fields(0).Value