Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA - Get parent window of worksheet

Tags:

excel

vba

I have a Sub that inserts a header from a template and freezes the top row of the active worksheet, which is written as,

Sub HeaderInsert(headerTemplate As Worksheet)
    headerTemplate.Rows("1:1").Copy
    ActiveSheet.Rows("1:1").Select
    ActiveSheet.Paste
    With ActiveWindow
        .SplitColumn = 0
        .SplitRow = 1
        .FreezePanes = True
    End With
End Sub

I want to turn it into a function which is passed the sheet to insert the header into. So that it would be written,

Function HeaderInsert(headerTemplate As Worksheet, contentSheet as Worksheet)

ActiveSheet becomes contentSheet, but how can I get the Window of contentSheet?

Also is a better way to do that copy and paste?

like image 723
cheezsteak Avatar asked Dec 19 '13 00:12

cheezsteak


People also ask

What is parent object in VBA?

Returns the object or collection that contains another object or collection. Read-only. Remarks. Most objects have either a Parent property or a Collection property that points to the object's parent object in this object model.

What is SH in VBA?

expression.SheetActivate (Sh) expression An expression that returns a Workbook object.

What is worksheet object in VBA?

In VBA, the worksheet object represents a single worksheet that is a part of the workbook's worksheets (or sheets) collection. Using the worksheet object, you can refer to the worksheet in a VBA code and refer to a worksheet you can also get access to the properties, methods, and events related to it.


1 Answers

I think you want contentSheet.Parent.Windows(1), e.g.:

Sub test()
Dim ws As Excel.Worksheet
Dim wb As Excel.Workbook

Set ws = ActiveSheet
Set wb = ws.Parent
Debug.Print wb.Windows(1).Caption
End Sub

As for the better way to paste: headerTemplate.Rows("1:1").Copy ActiveSheet.Rows("1:1")

More generally, you want to avoid Select unless necessary.

like image 123
Doug Glancy Avatar answered Sep 21 '22 08:09

Doug Glancy