我一直在尝试使用我尝试过的函数对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
的方式:Resume
,Resume Next
和Resume label
不带参数的Resume
会使代码在导致错误的行处恢复。显然,必须非常小心地使用此方法,因为您必须绝对确定已解决问题,否则最终将陷入无限循环。Resume Next
使代码在导致错误的行之后的行继续执行。Resume Label
与GoTo Label
几乎相同,但是您可以退出错误处理程序并恢复正常的代码执行。错误处理程序已重新启用。
关于vba - 数据透视表对象排序循环中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40124705/