【问题标题】:Type mismatch Error in VBA when creating ActiveX control drop down list创建 ActiveX 控件下拉列表时 VBA 中的类型不匹配错误
【发布时间】:2015-09-12 00:44:28
【问题描述】:

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

然后我在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 控件中选择值时,错误消息填充

运行时错误,类型不匹配

这里是调试模式的错误.AddItem Myrecordset![TgtField] 任何帮助

【问题讨论】:

  • 请提供更多上下文。 TargetChild 是什么?您使用的是哪种 ActiveX 控件?你在哪一行得到错误?
  • 当然我会更新查询更多..谢谢
  • 我更新了我的问题,希望你现在能理解。谢谢

标签: vba excel excel-2010


【解决方案1】:

试试

.AddItem Myrecordset.Fields(0).Value

【讨论】:

  • 您好 CharlieOscarDeltaEcho,感谢您的回答,我为此苦苦挣扎了一整天。我现在在组合框中有值。再次感谢。
猜你喜欢
  • 2021-02-19
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 2017-04-12
  • 2017-04-14
相关资源
最近更新 更多