使用不存在的filter处理错误
我已经写了一些VBA代码来创build应该被自动过滤的数据透视表。 有两个可能的filter: 0
和1
。 有可能两者都存在,但也可能只有其中之一存在。
我首先需要Excel将filter设置为0
,并将一些行复制到另一个表(这就是Call b02_articleunit0
所做的)。 如果这样做我希望Excel使用筛选器1
做同样的事情,但不幸的是它不工作。 即使两个滤波器都存在,只有第一个(在这种情况下为0
)将被处理。 但它也应该处理第二个filter,并保存工作簿在最后与Call SaveXLS
工作正常,如果它可以执行。
你有什么想法如何优化我的代码?
Sub PivotTable() [...] Dim pf As PivotField Set pf = ActiveSheet.PivotTables("PivotTable1").PivotFields("Abgleich_ME1_ME2") 'Remove existing filter pf.ClearAllFilters 'Filter on 0 On Error GoTo fehler0: pf.CurrentPage = "0" Call b02_articleunit0 Exit Sub fehler0: Worksheets("Übersicht").Range("D19").Value = "This filter isn't existing! (Filter 0)" Resume Next 'Filter on 1 On Error GoTo fehler1: pf.CurrentPage = "1" Call b02_articleunit1 Exit Sub fehler1: Worksheets("Übersicht").Range("D19").Value = "This filter isn't existing! (Filter 1)" Resume Next Call SaveXLS End Sub
编辑:由于误解,我会尽力描述我的问题。
Abgleich_ME1_ME2
列可能包含一些值,如下表所示。 第2
和3
栏描述了三种可能的情况。
1 | 2 | 3 --------------- 1 | 0 | 1 1 | 0 | 0 1 | 0 | 1 1 | 0 | 1
第一种情况: Abgleich_ME1_ME2
列中的所有值均为1
。 数据透视表将使用筛选器作为Abgleich_ME1_ME2
列Abgleich_ME1_ME2
。 由于此列仅包含1
,因此不存在filter0
。 所以如果我执行试图将filter设置为这个值的vba代码,就会出现错误。 无论如何,在这种情况下,我只想要调用b02_articleunit1
来执行。 否则我的数据将是错误的。
第二种情况:与第一种情况相同,但仅为0
。 最后只能调用b02_articleunit0
。
第三种情况:两个调用都应该执行,因为filter包含两个值。
你的问题在这里:
On Error GoTo fehler0: pf.CurrentPage = "0" Call b02_articleunit0 '-----------------remove this next line--------------------- Exit Sub '----------------------------------------------------------- fehler0: Worksheets("Übersicht").Range("D19").Value = "This filter isn't existing! (Filter 0)" Resume Next
当你的代码从b02_articleunit0
返回时,接下来的事情是退出子程序。
既然你想在你的error handling程序中有不同的错误信息,请尝试如下所示:
On Error GoTo fehler: pf.CurrentPage = "0" Call b02_articleunit0 pf.CurrentPage = "1" Call b02_articleunit1 Exit Sub fehler0: Worksheets("Übersicht").Range("D19").Value = "This filter isn't existing! (Filter " & pf.CurrentPage & ")" Resume Next
这样,你有一个error handling程序,它是在你的代码的末尾,它dynamic地显示基于您的PivotField设置的错误。
更新
根据您在OP中发布的示例数据,您确实需要find列中的内容,并根据该数据执行您的函数调用。 也许这样的事情:
Dim rng as Range Dim I as integer For I = 1 to 3 'assuming they're the first 3 columns, adjust as necessary set rng = ActiveSheet.Columns(i).find (What:=0, LookIn:=xlValues, LookAt:=xlWhole) if not rng is nothing then pf.CurrentPage = "0" Call b02_articleunit0 end if set rng = ActiveSheet.Columns(i).find (What:=1, LookIn:=xlValues, LookAt:=xlWhole) if not rng is nothing then pf.CurrentPage = "1" Call b02_articleunit1 end if Next set rng = Nothing
这将循环遍历3列中的每一列,search每一列0
和执行b02_articleunit0
如果find一个,然后search该b02_articleunit1
1
,如果find一个执行b02_articleunit1
。
如果那不是你所追求的,我还是非常迷失方向。