使用VBScript进行Excel列自动过滤

时间:2012-12-19 11:04:46

标签: excel-vba vbscript vba excel

假设我有一个如下矩阵:

     EMPID    Type Of employment
   #1 10            "T"
   #2 11            "P"
   #3 20            "P"
   #4 40            "T"
   #5 50            "T"
   #6 15            "P"
   #7 19            "T"

过滤后

    EMPID    Type Of employment
  #2 11            "P"
  #3 20            "P"
  #6 15            "P"

你们可以建议我在vbscript中如何做到这一点?我知道VBA的语法,但在VBScipt中不知道如何格式化?

过滤后如果我在#1列上使用CountA,我应该将行号设为3还是7?我在这里太困惑了。

更新

  objSheet2.Range("B1").AutoFilter 2, "Parent",,,False

要删除自动过滤,我使用了代码 - objSheet2.Rows("1:1").Select.AutoFilter,但收到错误Unable to get the select property of the Range Class

已更正 objSheet2.Range("B1").AutoFilter 2, "Parent",,,True                objSheet2.AutoFilterMode = False

查询: 一旦过滤了行,那么在循环过滤数据行时,如何识别过滤数据行的实际行数?

ANSWER

    For rowIndex=2 To objExcel1.Application.WorksheetFunction.CountA(ob1.Columns(1))
    If objSheet2.Rows(rowIndex).Hidden Then
        ' do nothing - row is filtered out
    Else
        MsgBox(rowIndex)
    End If
    Next 

这样我就得到了Filtered行的实际行号。如果您有任何更好的想法,请建议: - )

截屏

enter image description here

由于

1 个答案:

答案 0 :(得分:2)

我认为这会让你想要你更快一点。

objSheet2.Range("B1").AutoFilter 2, "Parent",,,True 

Dim rngFilter as Range
Set rngFilter = objXL.Application.Intersect(objSheet2.UsedRange,objSheet2.UsedRange.Offset(1),objSheet2.Columns(1)).SpecialCells(xlCellTypeVisible)

msgbox "Filtered range has " & rngFilter.Rows.Count & " rows."
'do with the range as you wish.

Dim cel as objXL.Range 'or just leave this off
For each cel in rngFilter
   msgbox cel.row
Next

objSheet2.AutoFilterMode = False

通过这种方式,您只能在过滤后选择可见单元格。然后,您可以根据需要将该范围加载到数组中或循环遍历它。