|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
增加一个worksheet_change()事件,输入条件后回车即可输出查询——
- <div>Option Explicit
- Private Sub Worksheet_Change(ByVal Target As Range)
- Select Case Target.Address
- Case "$T$3"
- Call QueryData(Target.Value)
- Case "$U$3"
- Call QueryData(Target.Offset(0, -1).Value, Target.Value)
- Case Else
- Exit Sub
- End Select
- End Sub
- Sub QueryData(wwlw As String, Optional jtbh As String)
- Dim wstDB As Worksheet, dic As Object, d
- Dim c As Range, s$, arrDB, arrRT, i%, j%, k%
- Set wstDB = Sheets("数据表")
- Set dic = CreateObject("SCRIPTING.DICTIONARY")
- With ActiveSheet.[C3:R3]
- For Each c In .Cells
- If Application.CountIf(wstDB.Rows(6), c.Value) = 0 Then '检查字段名称,将与[数据表$]中对不上的列出来
- s = s & c.Value & "、"
- Else '将字段名对应[数据表$]中的列号存入字典备用
- dic.Add c.Value, Application.Match(c.Value, wstDB.Rows(6), 0)
- End If
- Next
- End With
- If Len(s) > 0 Then
- MsgBox "下列字段名称无法与[数据表$]中的表头相匹配,请检查!" & vbCrLf & s, vbCritical
- Exit Sub
- End If
- arrDB = wstDB.Range("A8:AY" & wstDB.[B8].End(xlDown).Row)
- ReDim arrRT(Application.CountIf(wstDB.Columns(27), wwlw), dic.Count)
- d = dic.items
- For i = 1 To UBound(arrDB)
- If arrDB(i, 27) = wwlw And IIf(Len(jtbh) > 0, arrDB(i, 28) = jtbh, True) Then
- arrRT(k, 0) = k + 1 '序号
- For j = 0 To UBound(d)
- arrRT(k, j + 1) = arrDB(i, d(j))
- Next j
- k = k + 1
- End If
- Next i
- With ActiveSheet
- .[B4:R65536].ClearContents
- If arrRT(0, 0) > 0 Then
- .[B4].Resize(UBound(arrRT, 1) + 1, UBound(arrRT, 2) + 1) = arrRT
- Else
- MsgBox "没有查找到任何记录,请修改查询条件!", vbCritical
- End If
- End With
- Set wstDB = Nothing
- End Sub</div>
复制代码
|
评分
-
1
查看全部评分
-
|