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

前端 未结 3 2210
执念已碎
执念已碎 2020-12-16 18:31

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.

The only pie

相关标签:
3条回答
  • 2020-12-16 19:16

    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

    Windows("My Workbook.xls").DisplayGridlines = False
    
    0 讨论(0)
  • 2020-12-16 19:21

    We can either do it as "Comintern" suggested or activating the wanted sheets to execute de adequate line of code in a loop. I tried the code posted above in several ways and I'm posting the snippet that worked the best for me:

    Sub GridLines(Optional target As Worksheet, Optional display As Boolean = True)
    
        Dim oWnd As Window
        Dim oShView As WorksheetView
        If IsMissing(target) Or target Is Nothing Then
            For Each oShView In ActiveSheet.Parent.Windows(1).SheetViews
                oShView.DisplayGridlines = display
            Next
        Else
            For Each oShView In target.Parent.Windows(1).SheetViews
                If oShView.Sheet.Name = target.Name Then
                    oShView.DisplayGridlines = display
                    Exit For
                End If
            Next
        End If
        Set oShView = Nothing
        Set oWnd = Nothing
    End Sub
    

    Any feedback is very welcomed

    0 讨论(0)
  • 2020-12-16 19:31

    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:

    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 SheetViews collection. This should turn off gridlines for an arbitrary Worksheet object:

    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
    
    0 讨论(0)
提交回复
热议问题