首页 > 解决方案 > Excel for mac 隐藏功能区

问题描述

我正在 Excel for Mac (rev. 16.19) 之上开发一个 VBA 程序。因为我需要在(笔记本电脑)屏幕上有更多空间来显示结果,所以我想在打开工作簿时隐藏功能区。

到目前为止,我看到的所有解决方案都只能在 Windows 上运行,而不能在 Mac 上运行。我还尝试通过 Applescript 来使用 Macscript(见下文)。如果我从 scripteditor 运行该脚本,但未嵌入 VBA,则该脚本可以正常工作。

tell application "System Events" to tell process "Microsoft Excel"
    set frontmost to true
    keystroke "r" using {command down, option down}
end tell

在 VBA 中它看起来像这样:

Sub example()
Dim toggleRibbon As String
toggleRibbon = "tell application ""System Events"" to tell process ""Microsoft Excel""" & vbNewLine & _
                            "set frontmost to true" & vbNewLine & _
                            "keystroke ""r"" using {command down, option down}" & vbNewLine & _
                         "end tell"
Debug.Print toggleRibbon 'to check format (use of double quotes, etc.)
MacScript (toggleRibbon)
End Sub

在运行时执行此代码会出现错误 5

谁能解决我的问题?

标签: excelvbamacosapplescript

解决方案


根据 Excel 字典,命令应该是“显示功能区”或“扩展功能区”。但是,尝试从应用程序文档、窗口、工作簿、基本窗口中获取这些属性……总是返回“缺失值”。我猜微软没有为 Applescript 正确处理它。

因此,另一种解决方法是模拟用户操作。下面的脚本模拟了单击主菜单栏的菜单 5(“视图”)的第 4 项(“功能区”)。当然,在模拟之前必须激活 Excel(最前面):

tell application "Microsoft Excel" to activate
tell application "System Events" to tell process "Microsoft Excel" to click menu item 4 of menu 5 of menu bar 1

这个脚本是一个触发器:如果功能区对窗口可见,它就会被隐藏。如果功能区被隐藏,它就会变得可见。

如果要检查当前值,而不是触发器,则需要获取菜单的复选标记(缺失值或 ✓)这可以通过以下方式完成:

tell application "System Events" to tell process "Microsoft Excel" to set X to (value of attribute "AXMenuItemMarkChar" of menu item 4 of menu 5 of menu bar 1) is "✓"

如果色带可见,X 为真。

在 Excel 2011 上测试。其他 Excel 版本的菜单位置可能不同。


推荐阅读