excel vba筛选和分组
我在excel中有这张工作表,我需要应用excel vba筛选和分组,vba,excel,filtering,grouping,Vba,Excel,Filtering,Grouping,我在excel中有这张工作表,我需要应用自动筛选 假设“合同”从A1栏开始,而“评论”从B1栏开始。见下例: Contract Comment 111 A 111 b 111 c 222 d 222 f 222 g 333 d 333 f 333 A 444 b 444 d 444 c 合同评论 11
自动筛选
假设“合同”从A1栏开始,而“评论”从B1栏开始。见下例:
Contract Comment
111 A
111 b
111 c
222 d
222 f
222 g
333 d
333 f
333 A
444 b
444 d
444 c
合同评论
111 A
111 b
111摄氏度
222D
222F
222克
333d
333华氏度
333A
444 b
444 d
444摄氏度
我想筛选合同,以显示合同组/合同集(合同组/合同集示例为111),其中该组/合同集中的任何合同都有注释a。请参见下文:
注意:我有一些与我的应用程序相关的其他数据,但在本例中没有显示
Contract Comment
111 A
111 b
111 c
333 d
333 f
333 A
合同评论
111 A
111 b
111摄氏度
333d
333华氏度
333A
而且我希望能够通过任何不包含“A”的评论进行过滤。结果如下:
Contract Comment
222 d
222 f
222 g
444 b
444 d
444 c
合同评论
222D
222F
222克
444 b
444 d
444摄氏度
这将自动筛选合同列到合同集,该合同集中的任何合同的注释都为a 要筛选出值,您需要在数组中的文本之前添加一个,这似乎不起作用。因此,我在末尾添加了一个循环来遍历行manuall,并查看合同值是否在ContainsA数组中,如果是,则隐藏该行
Sub SomeSub()
Dim MyRange As Range, CommentRng As Range, ContractRng As Range
Dim ContainA As Variant
Dim i As Integer, k As Integer, r As Integer
'Getting the Total Rows of the Sheet
With ActiveSheet.UsedRange
LastRow = .Rows(.Rows.Count).Row
End With
'Setting the USedRange of the Sheet
Set MyRange = ActiveWorkbook.ActiveSheet.UsedRange
'Setting the Comment and Contract Ranges
Set CommentRng = ActiveWorkbook.ActiveSheet.Range(Cells(1, 2), Cells(LastRow, 2))
Set ContractRng = ActiveWorkbook.ActiveSheet.Range(Cells(1, 1), Cells(LastRow, 1))
'Filtering the Comment Column
MyRange.AutoFilter Field:=2, Criteria1:="A"
'Getting the number of visible cells in the Contract Range
' -1 to remove the First Row of the Comment headin
' -1 to set Array correctly, it Array(1) then the array( SomeValue, SomeOtherValue)
TotalA = ContractRng.SpecialCells(xlCellTypeVisible).Count - 2
'Setting the Array size
ReDim ContainA(TotalA)
'Setting the Array size
ReDim NotContainA(TotalA)
i = 0
'For each visible cell in Column 2 "Comment"
For Each cell In ContractRng.SpecialCells(xlCellTypeVisible)
'If the Value is "Comment"
If cell.Value = "Contract" Then
'Do nothing
Else
'Set the Cell value into the Array
ContainA(i) = cell
'Increment i
i = i + 1
End If
Next cell
ActiveSheet.ShowAllData
'Filitering the Column 1 Data, the Criteria1 needs to be a string Array
'Join(Array1) joins the Array as a String
'Split then splits the String as a String array
MyRange.AutoFilter Field:=1, Criteria1:=Split(Join(ContainA)), Operator:=xlFilterValues
ActiveSheet.ShowAllData
'If you want to hide the groups which contain "A"
'There is no "FILTEROUT" function
'so this must be done manually
For r = 1 To LastRow
For k = 0 To TotalA
If Cells(r, 1) = ContainA(k) Then
Rows(r).EntireRow.Hidden = True
End If
Next k
Next r
End Sub
您尝试过excel中的筛选选项吗?首先,欢迎使用StackOverFlow。仅供参考,本网站并非“请给我本网站的代码”网站。但更多的是“帮助我在代码中找到bug”网站。话虽如此,我还是回答了你下面的问题。有用的是使用Excel中的宏记录器尝试确定您想要做的事情,然后将其带到这里,这样我们就可以看到解决方案或我们可以在哪里为您提供帮助。我已经找到了与您类似的解决方案,但这不是我要寻找的。您的代码将只给出2个结果,但我希望能够筛选所有相同的合同,就像示例2所示。@Pero是否要筛选“合同”列?是的,我想它应该筛选合同和注释列。应该是这样的:如果合同111中有一个有注释“a”,则显示所有合同111及其注释。