vba - 数据透视表对象排序循环中的错误处理

标签 vba excel error-handling

我一直在尝试使用我尝试过的函数对VBA中的数据透视表对象进行排序:

Public Function PTSort(PTName As String, PTFieldName as String, SortArray As Variant)

Dim m as Integer: m = 1 'Row counter
Dim i as Long 'Dummy Variable for cycling

With ActiveSheet.PivotTables(PTName).PivotFields(PTFieldName)
    .Parent.ManualUpdate = True
    For i = LBound(SortArray) To UBound(SortArray)
        With .PivotItems(SortArray(m - 1)) 'For in-code array
            .Position = m
        End With
    m = m + 1
    Next i
    .Parent.ManualUpdate = False
End With

End Function

虽然这可以很好地与SortArray中的一组已知元素配合使用,但是我在排序时要遵循一个主列表(以便标准化几个数据透视表的几个顺序),其中数据透视表不必包含所有所述的数据透视表。因此,我将其改进为以下内容:
Sub PTSort(PTName As String, PTFieldName as String, SortArray As Variant)

Dim m as Integer: m = 1
Dim i as Long
Dim k As Integer: k = 1 'To cycle the position independently from the array in the event of disjoint.

With ActiveSheet.PivotTables(PTName).PivotFields(PTFieldName)
    .Parent.ManualUpdate = True
    For i = LBound(SortArray) To UBound(SortArray)
        On Error GoTo ERRHANDLER:
        With .PivotItems(SortArray(k)) 'After parsing from range of cells into VariantArray, then does one not require the "-1"
            .Position = m
        End With
    m = m + 1
ExitHandler:
    k = k + 1
    Next i
    .Parent.ManualUpdate = False
End With
GoTo ENDEND:

ERRHANDLER:
GoTo EXITHANDLER:

ENDEND:
End Sub

尽管OnError GoTo放置了多高,它似乎只能工作一次。

帮助将不胜感激。提前致谢!

最佳答案

这来自Visual Studio上的MSDN,但我认为它以相同的方式适用于VBA。

An "enabled" error handler is one that is turned on by an On Error statement. An "active" error handler is an enabled handler that is in the process of handling an error.

If an error occurs while an error handler is active (between the occurrence of the error and a Resume, Exit Sub, Exit Function, or Exit Property statement), the current procedure's error handler cannot handle the error. Control returns to the calling procedure


因此,在您的代码首次进入On Error GoTo ERRHANDLER之后,就启用了ERRHANDLER。然后,当发生错误时,ERRHANDLER被激活并处理该错误。当您GoTo EXITHANDLER保持 Activity 状态并仍然处理错误。 On Error GoTo ERRHANDLER在这一点上无效。
要重新启用ERRHANDLER,您需要使用Resume EXITHANDLER而不是GoTo EXITHANDLER

Resume语句上编辑。有三种使用Resume的方式:ResumeResume NextResume label 不带参数的Resume会使代码在导致错误的行处恢复。显然,必须非常小心地使用此方法,因为您必须绝对确定已解决问题,否则最终将陷入无限循环。Resume Next使代码在导致错误的行之后的行继续执行。Resume LabelGoTo Label几乎相同,但是您可以退出错误处理程序并恢复正常的代码执行。错误处理程序已重新启用。

关于vba - 数据透视表对象排序循环中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40124705/

相关文章:

ms-access - 如何在 vba(access) 中将变量设置为我的表单列表框之一?

excel - 根据变量excel vba选择整行

从宏 (Excel) 运行 R 脚本

excel - 用逗号分隔家庭地址

spring-mvc - Spring MVC和JDBC数据源

vba - 哪些 VB 或 VBA 解释器或编译器可用于 Windows 操作系统?

Excel VBA - 通过代码插入的公式不计算

r - 使用方法错误("select_"): no applicable method for 'select_' applied to an object of class "character"

php - PHP-包含或要求在oop的类文件中不起作用

excel - 改进选择案例