How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

前端 未结 6 898
终归单人心
终归单人心 2020-12-06 04:10

I am looking to programmatically freeze the top row of an Excel worksheet from VBA. The end goal is to produce the same effect as the View > Freeze Panes > Free

6条回答
  •  悲&欢浪女
    2020-12-06 04:36

    To expand this question into the realm of use outside of Excel s own VBA, the ActiveWindow property must be addressed as a child of the Excel.Application object.

    Example for creating an Excel workbook from Access:

    Using the Excel.Application object in another Office application's VBA project will require you to add Microsoft Excel 15.0 Object library (or equivalent for your own version).

    Option Explicit
    
    Sub xls_Build__Report()
        Dim xlApp As Excel.Application, ws As Worksheet, wb As Workbook
        Dim fn As String
    
        Set xlApp = CreateObject("Excel.Application")
        xlApp.DisplayAlerts = False
        xlApp.Visible = True
    
        Set wb = xlApp.Workbooks.Add
        With wb
            .Sheets(1).Name = "Report"
            With .Sheets("Report")
    
                'report generation here
    
            End With
    
            'This is where the Freeze Pane is dealt with
            'Freezes top row
            With xlApp.ActiveWindow
                .SplitColumn = 0
                .SplitRow = 1
                .FreezePanes = True
            End With
    
            fn = CurrentProject.Path & "\Reports\Report_" & Format(Date, "yyyymmdd") & ".xlsx"
            If CBool(Len(Dir(fn, vbNormal))) Then Kill fn
            .SaveAs FileName:=fn, FileFormat:=xlOpenXMLWorkbook
        End With
    
    Close_and_Quit:
        wb.Close False
        xlApp.Quit
    End Sub
    

    The core process is really just a reiteration of previously submitted answers but I thought it was important to demonstrate how to deal with ActiveWindow when you are not within Excel's own VBA. While the code here is VBA, it should be directly transcribable to other languages and platforms.

提交回复
热议问题