用户提示在VBA中过滤

时间:2017-02-02 17:13:42

标签: excel-vba vba excel

我试图通过从用户获取两个范围值来过滤我的数据集。我在两个变量't1'和amp;中使用这两个值。 'T2'。稍后,我使用这些变量来过滤我的数据集。但问题是这些用户提示值,我的过滤器无法正常工作。过滤在固定值下工作正常,但不适用于变量值。为方便起见提供代码:

`Sub GetUserInput()

Dim t1 As Long, t2 As Long
t1 = InputBox("Type the upper torque limit")
t2= InputBox("Type the lower torque limit")
Application.ScreenUpdating = False

'Below Code segment will find out the Time, Input Torque & Output speed    columns from the raw data set regardless of their position

Sheets(3).Activate
Range("A1").Select
Sheets(2).Activate
Columns("A").Select
Selection.Copy
Sheets(3).Activate
Selection.PasteSpecial
ActiveCell.Select
Sheets(2).Activate

'Find "D2TQSH" in Row 1
With Sheets(2).Rows(1)
Set t = .Find("D2TQSH", lookat:=xlPart)
'If found, copy the column to Sheet 2, Column A
'If not found, present a message
If Not t Is Nothing Then
Columns(t.Column).EntireColumn.Copy _
Destination:=Sheets(3).Range("B1")
Else: MsgBox "D2TQSH Not Found"
End If
End With

'Find "D2SPDFR" in Row 1
With Sheets(2).Rows(1)
Set t = .Find("D2SPDFR", lookat:=xlPart)
'If found, copy the column to Sheet 2, Column A
'If not found, present a message
 If Not t Is Nothing Then
 Columns(t.Column).EntireColumn.Copy _
 Destination:=Sheets(3).Range("C1")
 Else: MsgBox "D2SPDFR Not Found"
 End If
 End With

'Below code segment will filter out data based on the user input values

Sheets(3).Activate

With Sheet3
.AutoFilterMode = False
.Range("A1:C1").AutoFilter
.Range("A1:C1").AutoFilter Field:=2, Criteria1:=">=-t1", _
Operator:=xlAnd, Criteria2:="<=-t2"
End With

'Copy the filtered data.
Range("A1:C1", ActiveCell.End(xlDown)).SpecialCells(xlCellTypeVisible).Copy

'Paste filtered dataset to the Output Sheet
Sheets(4).Range("A1").PasteSpecial
Sheets(3).AutoFilterMode = False
`
`

1 个答案:

答案 0 :(得分:0)

当然它不起作用,你过滤列的值为“t1”和“t2”,注意 - 它们是字符串,文本值! 你应该使用

.Range("A1:C1").AutoFilter Field:=2, Criteria1:=">=" & CStr(-t1), _
 Operator:=xlAnd, Criteria2:="<=" & CStr(-t2)

这会将字符串“&gt; =”与您的t1和t2变量的值组合,转换为字符串。