2015年7月13日星期一

Excel VBA - Layout formatting for an exported excel worksheet

Sub main()

    Dim TheRange As Range
    ro = getRowCount(1)
    co = getColumnCount(1)
    
    Range(Cells(1, 1), Cells(ro, co)).Select
    Range(Cells(1, 1), Cells(ro, co)).VerticalAlignment = xlTop
    Range(Cells(1, 1), Cells(ro, co)).WrapText = True
    Range(Cells(1, 1), Cells(ro, co)).Font.Size = 8
    
    ' Set margin if need printing
    With ActiveSheet.PageSetup
        .LeftMargin = Application.InchesToPoints(0.5)
        .RightMargin = Application.InchesToPoints(0.5)
        .TopMargin = Application.InchesToPoints(0.5)
        .BottomMargin = Application.InchesToPoints(0.5)
        .HeaderMargin = Application.InchesToPoints(0.2)
        .FooterMargin = Application.InchesToPoints(0.2)
        .Orientation = xlLandscape
        .PaperSize = xlPaperA4
        .PrintTitleRows = ActiveSheet.Rows(1).Address
        '.Zoom = False
        '.FitToPagesWide = 1
        '.FitToPagesTall = 1
    End With
    
    ActiveSheet.DisplayPageBreaks = False
    
    ' Design as table
    Dim lstList As ListObject
    For Each lstList In ActiveSheet.ListObjects
        If lstList.Name = "Table1" Then
            ActiveSheet.ListObjects("Table1").Unlist
            Exit For
        End If
    Next
    
    Range(Cells(1, 1), Cells(ro, co)).Select
    ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes).Name = "Table1"
    ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight9"
    
    ' Set Width
    Range(Cells(1, 1), Cells(ro, co)).Columns.AutoFit
    
    For c = 1 To co
        Columns(c).Select
        If Columns(c).ColumnWidth > 15 Then
            Columns(c).ColumnWidth = 15
            If Cells(1, c).Value = "Goods and Services" Then Columns(c).ColumnWidth = 45
        End If
    Next c
    
    Cells(1, 1).Select
End Sub

Public Function getRowCount(sheet As Variant) As Integer
    If sheet = 0 Then
        getRowCount = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    Else
        getRowCount = Sheets(sheet).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End If
End Function

Public Function getColumnCount(sheet As Variant) As Integer
    If sheet = 0 Then
        getColumnCount = ActiveSheet.Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    Else
        getColumnCount = Sheets(sheet).Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    End If
End Function

沒有留言:

發佈留言