如何在不使用 ActiveWindow 的情况下使用 VBA 关闭 excel 中的网格线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40368373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:37:05  来源:igfitidea点击:

How can I turn off gridlines in excel using VBA, without using ActiveWindow

excelvbaexcel-vba

提问by tempidope

I have a VBA macro over Excel 2013 which generate a separate excel report. In this excel report that is created, I would like to turn off the GridLines.

我在 Excel 2013 上有一个 VBA 宏,它生成一个单独的 excel 报告。在创建的这个 excel 报告中,我想关闭 GridLines。

The only piece of code that I come across to make this happens is as below

我遇到的唯一一段代码如下

ActiveWindow.DisplayGridlines = False

However, this excel is generated in the background i.e.,

然而,这个excel是在后台生成的,即,

Dim appObject As New Excel.Application
appObject.Visible = False

Which means that this report is not the ActiveWindow. Is there an alternate way of turning off the gridlines without using the ActiveWindow object?

这意味着该报告不是 ActiveWindow。是否有另一种方法可以在不使用 ActiveWindow 对象的情况下关闭网格线?

回答by Comintern

If you have a reference to the workbook, you can just iterate over all of the Windows in its collection. If the application isn't visible, you should only get 1 but it's safer than trying to hard code an index:

如果您有对工作簿的引用,则只需遍历其集合中的所有 Windows。如果应用程序不可见,您应该只得到 1,但这比尝试硬编码索引更安全:

Private Sub ToggleGridLines(target As Workbook)
    Dim wnd As Window
    For Each wnd In target.Windows
        wnd.DisplayGridlines = False
    Next
End Sub

Note that this will set change the display on the active worksheet in the workbook - why this is a property of the window and not the worksheet is beyond me.

请注意,这将设置更改工作簿中活动工作表上的显示 - 为什么这是窗口的属性而不是工作表超出我的范围。

EDIT:

编辑:

Thanks to the link that @Tim shared, I realized I'd completely spaced off the SheetViewscollection. This should turn off gridlines for an arbitrary Worksheetobject:

感谢@Tim 分享的链接,我意识到我已经完全脱离了SheetViews收藏。这应该关闭任意Worksheet对象的网格线:

Private Sub TurnOffGridLines(target As Worksheet)
    Dim view As WorksheetView
    For Each view In target.Parent.Windows(1).SheetViews
        If view.Sheet.Name = target.Name Then
            view.DisplayGridlines = False
            Exit Sub
        End If
    Next
End Sub

回答by Tim

The ActiveWindow is a member of the Windows objects collection. As with any collection, simply refer to the actual window by name rather than by specifying the active window. eg

ActiveWindow 是 Windows 对象集合的成员。与任何集合一样,只需通过名称而不是通过指定活动窗口来引用实际窗口。例如

Windows("My Workbook.xls").DisplayGridlines = False