【问题标题】:VBA Using Sendkey to execute Excel HotkeysVBA 使用 Sendkey 执行 Excel 热键
【发布时间】: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”覆盖数据透视信息的危险。我已经注释掉了我原来的循环,它在处理大量数据时花费的时间太长了。

有什么想法吗?我只是不耐烦使用循环方法吗?

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    不,你没有不耐烦!如果您使用的是 2007 或更高版本,请使用:

        Application.CommandBars.ExecuteMso "PivotTableSubtotalsDoNotShow"
    

    【讨论】:

    • 哇,这太棒了。我以前从未见过这种情况。所以唯一的问题是,如果他们在 Subtotals 已经关闭的情况下尝试运行它,则会引发错误。如果小计已经关闭,我如何正确地检查以仅运行此命令?
    • 我尝试使用不同的数据透视表,现在没有问题。我会继续关注它,谢谢你的提示,这太棒了!
    猜你喜欢
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 2017-08-08
    • 2015-11-30
    • 1970-01-01
    • 2020-05-10
    相关资源
    最近更新 更多