【发布时间】:2021-09-22 02:49:02
【问题描述】:
我的 xlsm 文件中有一个名为“DATA”的数据连接。
我创建了组合框并输入了范围内的值。
现在我需要根据组合框(下拉列表)中的值返回一个结果集。例如如果下拉列表中的值为“CompanyXYZ”,则需要返回来自“DATA”的查询,但只返回 CompanyXYZ 的数据。
等效的sql是:
"SELECT * FROM [query] where [column] = combobox
问题 #1
下面是我的工作表(“数据”)。它有一个由 SQL 查询返回的表。其中一列是 Debtor_Name。它有 8500 多行,但只有 90 行是唯一的。
在我的另一张表中,我有一个 ActiveX 组合框,它需要返回 DATA.Debtor_name 列中的所有唯一值(90 个唯一值)。
问题 #1 的示例 VBA:
Sub Populate_Combobox_Worksheet()
'The Excel workbook and worksheets that contain the data, as well as the range placed on that data
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnData As Range
'Variant to contain the data to be placed in the combo box.
Dim vaData As Variant
'Initialize the Excel objects
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("DATA")
'Set the range equal to the data, and then (temporarily) copy the unique values of that data to the L column.
With wsSheet
Set rnData = .Range(.Range("D1"), .Range("D10000").End(xlUp))
rnData.AdvancedFilter Action:=xlFilterCopy, _
CopyToRange:=.Range("X1"), _
Unique:=True
'store the unique values in vaData
vaData = .Range(.Range("X2"), .Range("X10000").End(xlUp)).Value
'clean up the contents of the temporary data storage
.Range(.Range("X1"), .Range("X10000").End(xlUp)).ClearContents
End With
'display the unique values in vaData in the combo box already in existence on the worksheet.
With wsSheet.OLEObjects("ComboBox1").Object
.Clear
.List = vaData
.ListIndex = -1
End With
End Sub
问题 #2。
现在最终用户需要从组合框中选择一个债务人名称,然后单击刷新数据。此 DATA REFRESH 将只需要从其中 debor_name = [组合框中的选定值] 的 SQL 中提取数据
我询问了问题 #2,因为我不知道我的组合框有问题(问题 #1);但是,我可以以某种方式处理它;现在只需要问题 #2 的帮助。
【问题讨论】:
-
请提供一些数据进行测试。似乎使用 for 循环来实现您的目标,但有必要知道您有多少列包含数据。另一种方法应该是在 VBA 中使用 SQL
-
嗨@GGG 感谢您的回复。我已经添加了有关该问题的更多信息。提前感谢您的帮助。
-
您可以使用 ADODB 为所欲为。阅读这个问题和答案,看看它是否为您指明了正确的方向。 stackoverflow.com/questions/19755396/…