我正在提取工作组织的报告,并希望通过唯一的ID值进行查找和过滤。通过用户表单中的文本框输入的公共属性(此数字在其他场合使用,因此它是公共的)指定要过滤的唯一ID。
我正在过滤9个不同的经理级别,分别在AU,AW,AY,BA,BC,BE,BG,BI和BK列中,它们都位于第3行。因此,我有“ A3:BK3”列但仅在“ AU3:BK3”之间进行过滤以提取较早列中的数据。
我没有收到任何错误和代码过滤器,但是它过滤了错误的列,因此未显示任何结果。我也分解了代码。
代码:
Dim Rng1 As Range
Dim Rng2 As Range
....
Dim Rng9 As Range
Set Rng1 = Range("AU:AU")
Set Rng2 = Range("AW:AW")
....
Set Rng9 = Range("BK:BK")
If Rng1.Find(WWID) Is Nothing Then
Range("AU3").AutoFilter Field:=47, Criteria1:="=*" & WWID & "*"
Else
If Rng2.Find(WWID) Is Nothing Then
Range("AW3").AutoFilter Field:=49, Criteria1:="=*" & WWID & "*"
Else
......
If Rng9.Find(WWID) Is Nothing Then
Range("BK3").AutoFilter Field:=63, Criteria1:="=*" & WWID & "*"
Else
MsgBox "You cannot get this code right can you?"
End If
......
End If
End If
我为此创建了一个测试工作簿,并用垃圾数据填充了它。然后,我创建了一个基本的用户窗体,该窗体只有一个文本框(名为txtUniqueID
)和一个按钮(名为CommandButton1
)。在文本框中输入我要查找的ID,然后单击按钮以运行搜索和过滤器(如果找到)。验证它是否按预期工作。您应该能够适应您的需求。这是完整的用户表单代码。请注意,在sub外部顶部的Dim WWID As Variant
,因为您说这是一个公共变量(这也可能在标准模块中,而不是Dim
而是Public
,为方便起见,我只是这样做了测试)。
Dim WWID As Variant
Private Sub CommandButton1_Click()
If Len(Trim(Me.txtUniqueID.Text)) = 0 Then
Me.txtUniqueID.SetFocus
MsgBox "Must provide a Unique ID"
Exit Sub
End If
WWID = Trim(Me.txtUniqueID.Text)
'Explicitly define your workbook and worksheet where the data is
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim aColumns() As String
aColumns = Split("AU,AW,AY,BA,BC,BE,BG,BI,BK", ",")
Dim bFound As Boolean
bFound = False
Dim rFound As Range
Dim vColumn As Variant
For Each vColumn In aColumns
Set rFound = ws.Columns(vColumn).Find(WWID, , xlValues, xlPart)
If Not rFound Is Nothing Then
bFound = True
MsgBox "Found [" & WWID & "] in column " & vColumn
With ws.Columns(vColumn)
.AutoFilter 1, rFound.Value
MsgBox "filtered"
'Do stuff with the filtered data here
.AutoFilter 'Remove filter afterwards
End With
Exit For
End If
Next vColumn
If bFound = False Then MsgBox "Unique ID [" & WWID & "] not found"
End Sub