【发布时间】: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