【问题标题】:vba SpecialCells(xlCellTypeVisible) not working correctly when looping through pivot items in a filtervba SpecialCells(xlCellTypeVisible)在过滤器中循环遍历数据透视项目时无法正常工作
【发布时间】:2019-01-09 10:31:26
【问题描述】:

我正在使用下面的代码在数据透视表的过滤器中循环浏览项目,然后复制过滤后的结果。

但由于某种原因,代码无法解释没有结果的项目,而是似乎复制了以前的结果。

我在代码中对不会显示任何结果的项目进行错误处理,但它似乎不起作用 - 遍历代码时,它会跳过我放置在那里的“如果”以捕捉“无” .

然后(当它到达代码的复制/粘贴部分时)复制在前一个循环的过滤器中选择的最后一个项目下可见的(现在隐藏的)单元格。

我错过了代码的结尾,因为它有点冗长并且一切正常,只是可见单元格的部分我似乎无法正常工作。

Sub Bulletin_Chase()

Dim pt As PivotTable
Dim pi As PivotItem
Set pt = Worksheets("By User").PivotTables("PivotTable1")

Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String

For Each pi In pt.PageFields("Supplier").PivotItems
  pt.PageFields("Supplier").CurrentPage = pi.Name

With Range("Filters")
    .AutoFilter Field:=2, Criteria1:=Array("false"), Operator:=xlFilterValues
End With

On Error Resume Next
Set rng = Worksheets("By User").Range("Bulletin_List").SpecialCells(xlCellTypeVisible)

If rng Is Nothing Then
    Worksheets("By User").AutoFilterMode = False
    Range("Filters").AutoFilter
    GoTo Continue
End If

等等……

真的很努力解决这个问题,所以非常感谢各位天才的任何帮助。

【问题讨论】:

  • 注释掉/删除错误处理。你得到什么错误,在哪一行?当您说它跳过“If”语句时,它是否转到If rng is Nothing Then 行,下一步是转到End If
  • 我没有收到来自 VBA 的错误消息,代码运行,但是当它应该识别没有可见的单元格并遵循错误处理时,它会复制“以前的”循环结果 - 这会将它带到'For Each' 的'Next' 部分。所以是的,它到达了“if rng is Nothing Then”并直接移动到“End If”,而不是做它应该做的事情。

标签: excel vba


【解决方案1】:

尝试设置 rng 时,如果没有可见单元格,则分配失败并跳到下一行代码。此过程不会将 rng 设置为 Nothing。它什么也不做,这让 rng 保留了上次循环运行时的值。

最简单的解决方案是在尝试将其分配给可见单元之前强制 rng 为空。这样,如果分配失败,您将在测试 rng = nothing 时成功检测到失败:

Range("Filters").AutoFilter Field:=2, Criteria1:=Array("false"), Operator:=xlFilterValues 'No need for a With block if you're only performing 1 method

set rng = Nothing 'Clear the rng variable before trying to assign a new range to it
On Error Resume Next
Set rng = Worksheets("By User").Range("Bulletin_List").SpecialCells(xlCellTypeVisible)
On Error Goto 0 'Restore normal On Error behaviour to trap any other unexpected errors

【讨论】:

    猜你喜欢
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    相关资源
    最近更新 更多