Excel VBA获取一张工作表上的值作为另一工作表上搜索结果的参数

时间:2017-09-26 13:59:10

标签: excel vba excel-vba

我有一张名为“lookup”的工作表,在该工作表的单元格B2中,用户可以输入部门代码(例如:190)并选择“搜索”按钮: enter image description here

一旦他们点击搜索按钮,就会将他们带到名为“department_lookup”的工作表中,其中A列的帐户代码中包含部门代码190,而B列中则有帐户代码说明。但是,在单元格C1中,我想要搜索填充单元格C1的值,这样表单“department_lookup”中的查询可以刷新以显示正确的数据。这是“department_lookup”的表格: enter image description here

在A栏和A栏中B将是一个列表,具体取决于其中有多少个帐户代码具有部门代码190。

基本上,工作表 department_lookup 中的数据是动态查询,我希望单元格C1是参数值,它会改变查询以显示用户在单元格中搜索的帐户代码工作表中的B2 查找

这是我用于表查找的代码:

On Error GoTo Done:
        If Target.Column = 2 And Target.Cells.Count = 1 Then
            Cancel = True
            mycell = Sheets("department_lookup").Range("$C$1").Value
            If mycell = " " Then GoTo Done:
            Sheets("department_lookup").Activate
        End If
Sheets("acct_codes").Visible = False
Sheets("dept_list").Visible = False 
Cancel = True
Application.ScreenUpdating = True               
End Sub

这是我用于表 department_lookup 的vba:

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$C$1" Then
With ActiveWorkbook.Connections("deptlookup").OLEDBConnection
.CommandText = "select seg1_code+'-'+seg2_code+'-'+seg3_code+'-'+seg4_code as account_code, account_description from glchart as GL where GL.inactive_flag = 0 and seg2_code='" & Range("C1").Value & "' order by seg1_code"
End With
ActiveWorkbook.Connections("deptlookup").Refresh
End If
End Sub

目前,当我手动将单元格C1的值更改为不同的部门代码时, department_lookup 中的查询将更改为显示正确的代码,但我认为我的问题是将C1正确设置为相等用户在工作表查找中的单元格B2中搜索的内容。任何人都可以帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

单击提交按钮,将该工作表的c1设置为等于初始工作表的单元格,然后按C1过滤,例如:

Sheets("department_lookup").Cells(1, 3).Value = Sheets("lookup").Cells(2, 2).Value
With Sheets("department_lookup")
    .Range(.Cells(1, 1), .Cells(LR, LC)).AutoFilter field:=3, Criteria1:=.Cells(1, 3).Value, VisibleDropDown:=True
End With

您可以将LR定义为最后一行,将LC定义为最后一列。