Excel VBA - 获取工作表的父窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20671374/
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-12 01:01:35  来源:igfitidea点击:

Excel VBA - Get parent window of worksheet

excelvbaexcel-vba

提问by cheezsteak

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,它被写为,

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)

ActiveSheetbecomes contentSheet, but how can I get the Windowof contentSheet?

ActiveSheetcontentSheet,但我怎么能得到WindowcontentSheet

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

还有更好的方法来进行复制和粘贴吗?

回答by Doug Glancy

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

我想你想要contentSheet.Parent.Windows(1),例如:

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")

至于更好的粘贴方式: headerTemplate.Rows("1:1").Copy ActiveSheet.Rows("1:1")

More generally, you want to avoid Selectunless necessary.

更一般地说,除非必要否则您希望避免Select