gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:58:54 40 4
gpt4 key购买 nike

我一直在尝试使用我尝试过的函数对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/

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