简体   繁体   English

使用Excel 2003 VBA使用组合框和文本框的多个高级筛选器

[英]Multiple advanced filter using a combobox and a textbox with Excel 2003 VBA

I searched the topics carefully before I post my question and could not actually find a match for my case. 在发布问题之前,我仔细搜索了主题,但实际上找不到适合我的案例的匹配项。

I have created a large database for the needs of my current job using Excel 2003. I have established an Advanced Filter with eight possible criteria options. 我已经使用Excel 2003创建了一个适合当前工作需要的大型数据库。我已经建立了具有八个可能条件选项的高级筛选器。 Now I have to expand the interface and functionality by setting up a UserForm. 现在,我必须通过设置用户窗体来扩展界面和功能。 Unfortunately, I feel if I don't finish this it can cost me my job. 不幸的是,我觉得如果我不做完这会浪费我的工作。

The purpose of my UserForm is to ease the search in the database by allowing the user to specify a criteria from three dropboxes (cboSelectCategory, cboSelectStructure, cboSelectSX). 我的UserForm的目的是通过允许用户从三个保管箱(cboSelectCategory,cboSelectStructure,cboSelectSX)中指定条件来简化数据库中的搜索。 The combobox cboSelectCategory is accommodating the heads of my criteria range which is CriteriaCategory (see figure 1). 组合框cboSelectCategory可以容纳我的CriteriaCategory标准范围的头(请参见图1)。 The other two, cboSelectStructure and cboSelectSX are populated from two separate dropdown lists which every piece of information in the database has both (in my database every single row stands for a document and I have three sheets of documents - active documents, cancelled documents and pending documents). 其他两个cboSelectStructure和cboSelectSX是从两个单独的下拉列表中填充的,数据库中的每条信息都包含两个列表(在我的数据库中,每行代表一个文档,而我有三张文档-活动文档,已取消文档和待处理文档)文件)。 All three cbo's should be using one and the same textbox (txtSearch) for entering the search keyword/s. 所有三个cbo都应使用一个相同的文本框(txtSearch)输入搜索关键字。 And also, if nothing is selected from the cbo's, the textbox input text should serve as a search string throughout the entire database matching data even partially (no mater if data begins or ends with the search string symbols). 而且,如果没有从cbo中选择任何内容,则文本框输入文本应该用作整个数据库中甚至部分匹配数据的搜索字符串(如果数据以搜索字符串符号开头或结尾,则不重要)。

Here is what my code looks like so far. 到目前为止,这是我的代码。 I've added comments and links to pictures to illustrate my case. 我添加了评论和图片链接来说明我的情况。

称为CriteriaCategory的标准范围的概述

The range CriteriaCategory includes the headers of the columns BN to BU (DOC NUMBER, NAME IN ENGLISH, including STRUCTURE). 范围CriteriaCategory包括BN至BU列的标题(DOC NUMBER,英文名称,包括STRUCTURE)。 The cells below them (row nr. 8) are used to enter the search string depending on the type of data I am searching for. 它们下面的单元格(第8行)用于根据我要搜索的数据类型输入搜索字符串。 For example, if I'm looking for the document number, I'll be typing a search string in the cell just below DOC NUMBER and so on. 例如,如果要查找文档编号,我将在DOC NUMBER下方的单元格中键入搜索字符串,依此类推。 These headers are listed in my cboSelectCategory combobox in the UserForm on the picture below. 这些标题列在我的cboSelectCategory组合框中的下图所示的用户窗体中。

带有命名约定的UserForm外观

I am trying to make Excel put whatever I type in the keyword textbox in the correct cell in the worksheet depending on what I have chosen in cboSelectCategory and then run the advanced filter. 我试图使Excel根据我在cboSelectCategory中选择的内容,将我在关键字文本框中键入的任何内容放在工作表的正确单元格中,然后运行高级筛选器。 Furthermore I need to make Excel search the entire database if the three cbo's are left blank by the user and return every match, no matter where on the worksheets (I have three) it is found and no matter if it is in the beginning of the cell text or at the end. 此外,如果用户将三个cbo留为空白,则我需要使Excel搜索整个数据库,并返回每个匹配项,无论在工作表上的什么位置(我有三个)都被找到,并且无论它是否位于表的开头。单元格文本或末尾。

I haven't got a slightest clue how to tackle this situation. 我没有丝毫线索来解决这种情况。 Any ideas are appreciated, code snippets too. 任何想法都值得赞赏,代码片段也是如此。 Mine looks like this: 我的看起来像这样:

   Private Sub cmdSearch_Click()

        If Me.cboSelectCategory.Value = "" Or Me.cboSelectStructure.Value = "" Or Me.cboSelectSX.Value = "" Then
            Me.txtSearch.Value = Sheet6.Cells("BS8").Value

            AdvancedFilterCategory

        Else
            Me.cboSelectCategory.Value = Range("CriteriaCategoryFirstRow").Find(what:=Me.cboSelectCategory.Value, _
            LookIn:=xlValues)
            Me.txtSearch.Value = Range("CriteriaCategoryFirstRow").Offset(1, 0).Value

            AdvancedFilterCategory

        End If

    End Sub

My idea using the range CriteriaCategoryFirstRow (the name is a hint) was to make Excel search the first row of the CriteriaCategory range to find a match of the cboSelectCategory value and then go one cell down, put the value from the keyword textbox (txtSearch) and execute the advanced filter. 我使用范围CriteriaCategoryFirstRow(名称是提示)的想法是使Excel搜索CriteriaCategory范围的第一行以找到cboSelectCategory值的匹配项,然后向下移动一个单元格,然后从关键字文本框(txtSearch)中输入值并执行高级过滤器。 Unfortunately, this doesn't work and I think my idea may be just wrong. 不幸的是,这行不通,我认为我的想法可能是错误的。

Not sure if I totally understand your issue per se; 不知道我是否完全了解您的问题; however if you are trying to return records from a database I'd recommend dynamically building a SQL string based on the form values entered. 但是,如果您尝试从数据库返回记录,我建议根据输入的表单值动态构建SQL字符串。

Here's some sample code connecting to an Access Database, and selecting some data based on Excel cells being filled out: 以下是一些示例代码,它们连接到Access数据库,并根据填写的Excel单元格选择一些数据:

Const adCmdText = &H1
Public Sub Example()

Dim DbConnection               As Object
Dim AccessRecordSet            As Object

Set DbConnection = CreateObject("ADODB.Connection")
Set AccessRecordSet = CreateObject("ADODB.Recordset")

Set DbConnection = New ADODB.Connection

'Lookup your relevant Connection String Online
'www.connectionstrings.com :)
With DbConnection
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .ConnectionString = "Data Source='C:\Users\SampleUserName\Desktop\MYDATABASE.accdb'; Persist Security Info=False;"
    .Open
End With

'To Customize your SQL I'd do something like...
'I'm assuming all ANDs; hopefully this is illustrative enough to communicate the general idea
SqlWhere = "Where "


If Range("A1").Value <> "" Then
    SqlWhere = SqlWhere & "[MyTableName].[MyFieldName] = " & Range("A1").Value & " AND " 'Add apostrophes on either side of the double quotes if the variable is TEXT
End If

If Range("B1").Value <> "" Then
    SqlWhere = SqlWhere & "[MyTableName].[MyOtherField] = " & Range("B1").Value & " AND "
End If

StrSql = "SELECT * FROM [MyTableName] "

'Remove the last AND applicable
If SqlWhere = "Where " Then
    SqlWhere = ""
Else
    SqlWhere = Left(SqlWhere, Len(SqlWhere) - 4)
End If

StrSql = StrSql & SqlWhere

AccessRecordSet.Open StrSql, DbConnection, adOpenStatic, adLockOptimistic, adCmdText

'This will paste the recordset to range you specify below
Range("A2").CopyFromRecordset AccessRecordSet

MsgBox "There are " & AccessRecordSet.RecordCount & " record(s)!"

End Sub

Hopefully this is illustrative of how to build a dynamic SQL string. 希望这可以说明如何构建动态SQL字符串。 You can use that to power your query and return the relevant results you are after. 您可以使用它来增强您的查询并返回所需的相关结果。 You can even do SQL queries in Excel if you already have the data loaded there, just look up the relevant connection string. 如果您已经在其中加载了数据,甚至可以在Excel中执行SQL查询,只需查找相关的连接字符串即可。

Hopefully this helps 希望这会有所帮助

==Ryan ==瑞安

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM