【发布时间】:2016-02-11 00:38:53
【问题描述】:
我知道 sendkeys 被认为是糟糕和危险的,但我正在努力弄清楚如何最好地处理 VBA 中的问题,而不是前端 Excel。
我编写了一个个人宏,用于设置一个未知的数据透视表来重复所有标签,设置为表格,对升序字段列表进行排序,最后隐藏小计。一切正常,除了小计需要一个循环,当有大量数据时,这个循环可能需要很长时间。奇怪的是,如果您只是从前端控件中关闭小计,那是即时的。因此,使用 Sendkey 会比实际循环更快。 (Sendkey 正在执行热键按下以执行关闭小计)
Sub formatpivotTable()
Dim pivotName As Variant
Dim pf As pivotField
On Error Resume Next
pivotName = ActiveCell.PivotTable.Name
If pivotName = "" Then
MsgBox "You did not select a pivot table"
Exit Sub
End If
ActiveSheet.PivotTables("" & pivotName & "").ManualUpdate = True
With ActiveSheet.PivotTables("" & pivotName & "")
.RepeatAllLabels (xlRepeatLabels)
.RowAxisLayout (xlTabularRow)
.FieldListSortAscending = True
'For Each pf In .PivotFields
' pf.Subtotals(1) = True
' pf.Subtotals(1) = False
'Next
End With
ActiveSheet.PivotTables("" & pivotName & "").ManualUpdate = False
'Remove the Loop and instead use the Front End Hotkey
ActiveSheet.Activate 'Normally using activate is bad, but maybe it's good here to ensure your sendkeys hit excel? not even sure this prevents it
Application.SendKeys "%", True
Application.SendKeys "{J}", True
Application.SendKeys "{Y}", True
Application.SendKeys "{T}", True
Application.SendKeys "{D}", True
End Sub
当它工作时,它工作得很好。整个过程不到一秒钟就完成了。但是我觉得如果出现问题,您的发送密钥仍然存在用“JYTD”覆盖数据透视信息的危险。我已经注释掉了我原来的循环,它在处理大量数据时花费的时间太长了。
有什么想法吗?我只是不耐烦使用循环方法吗?
【问题讨论】: