Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

excel

vba

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 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.,

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?

like image 778
tempidope Avatar asked Nov 01 '16 20:11

tempidope


2 Answers

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
like image 197
Comintern Avatar answered Nov 08 '22 02:11

Comintern


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
like image 32
Tim Avatar answered Nov 08 '22 01:11

Tim