gpt4 book ai didi

vba - Excel 数组过滤器

转载 作者:行者123 更新时间:2023-12-04 20:54:49 24 4
gpt4 key购买 nike

我在 Excel 的四列中有数据。第三列(“C”)包含一个带有国家名称的字符串,例如“国家名称是中国”。该字符串未标准化,因此我无法使用左/右/中等字符串函数。我正在创建一个宏来过滤六个国家(埃及、美国、中国、俄罗斯、日本和乌干达)。到目前为止,我可以使用以下宏获得两个国家:

Sub Countries ()
Activesheet.Range("A1:D1000").Autofilter Field:=3, Criteria1:=Array("*Japan*","*China*"),Operator:=xlFilterValues
End Sub

这是有效的,我能够过滤这两个国家。但是,当我添加更多国家/地区时,Excel 不会显示国家/地区并且不返回任何行。
我不确定我做错了什么,我希望有人可以帮助我

最佳答案

您可以遍历国家/地区:

Option Explicit

Sub main()
Dim filter As Variant
Dim countriesRng As Range

Set countriesRng = Range("A1") ' initial dummy range to use Union() without checking for 'countriesRng' being 'Nothing'
With Range("A1:D" & cells(Rows.Count, "C").End(xlUp).row) ' reference columns A:D from row 1 down to column C last not empty row
For Each filter In Array("Egypt", "USA", "China", "Russia", "Japan", "Uganda") ' loop through countries
.AutoFilter Field:=3, Criteria1:="*" & filter & "*" ' filter current country
If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then Set countriesRng = Union(countriesRng, .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible)) ' if any filtered cells other than header then add them to 'countriesRng'
Next
.parent.AutoFilterMode = False

Set countriesRng = Intersect(countriesRng, Range("C:C")) ' get rid of the initial dummy range
If Not countriesRng Is Nothing Then ' if any filtered country
.Resize(.Rows.Count - 1).Offset(1).EntireRow.Hidden = True ' hide all records
countriesRng.EntireRow.Hidden = False ' unhide ones with filtered countries
End If
End With
End Sub

关于vba - Excel 数组过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50438870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com