简体   繁体   中英

Copying Format of one excel sheet to another excel worksheet using VBA

Is it possible to copy format of one excel sheet to another worksheet using VBA.

Like manually we can do by selecting entire sheet and then click on format button. And then select other worksheet and format will be copied. Is it possible to do by code.

Thanks & Regards Sahil Chaudhary

Absolutely. Below is sample code.

see https://msdn.microsoft.com/en-us/library/office/ff837425.aspx

Sub Wsh_PasteSpecial()
Dim WshSrc As Worksheet
Dim WshTrg As Worksheet

Rem Set working worksheets
Set WshSrc = ThisWorkbook.Worksheets("Source")
Set WshTrg = ThisWorkbook.Worksheets("Target")

    WshSrc.Cells.Copy
    With WshTrg.Cells
        .PasteSpecial Paste:=xlPasteColumnWidths
        .PasteSpecial Paste:=xlPasteFormats
        .PasteSpecial Paste:=xlPasteFormulasAndNumberFormats
        Application.CutCopyMode = False
    End With    
End Sub

Find below the full code to paste the format of one Worksheet named "Source" , including Color, ColumnWidth, RowHeight, Comment, DataValidation, except the contents ( Values, Formulas ) of the cells to all other Worksheets in the same Workbook excluding a List of Worksheets as an Array

Option Explicit

Sub Wsh_PasteSpecial_Test()
Dim aWshExcluded As Variant, vWshExc As Variant
aWshExcluded = Array("Exclude(1)", "Exclude(2)")

Dim WshSrc As Worksheet
Dim WshTrg As Worksheet

Rem Set Source Worksheet
Set WshSrc = ThisWorkbook.Worksheets("Source")
Application.ScreenUpdating = 0

    Rem Process All Worksheets
    For Each WshTrg In WshSrc.Parent.Worksheets

        Rem Exclude Worksheet Source
        If WshTrg.Name <> WshSrc.Name Then

            Rem Validate Worksheet vs Exclusion List
            For Each vWshExc In aWshExcluded
                If WshTrg.Name = vWshExc Then GoTo NEXT_WshTrg
            Next

            Rem Process Worksheet Target
            With WshTrg.Cells
                WshSrc.Cells.Copy
                .PasteSpecial Paste:=xlPasteFormats     'Source format is pasted.
                .PasteSpecial Paste:=xlPasteComments    'Comments are pasted.
                .PasteSpecial Paste:=xlPasteValidation  'Validations are pasted.
                Application.CutCopyMode = False
                Application.Goto .Cells(1), 1
    End With: End If:

NEXT_WshTrg:

    Next  

Application.Goto WshSrc.Cells(1), 1
Application.ScreenUpdating = 1

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM