格式化每个工作表中的单元格

时间:2018-07-31 12:17:44

标签: excel vba

我更改了工作表中单元格M1的颜色和其他内容。我需要在工作簿的所有工作表中执行相同的操作(所有工作表中的同一单元格)。

大约有40张纸,因此我需要使用VBA对该任务进行编程。

我记录了该过程,但是不知道如何在所有工作表中编写代码来实现此目的。

我记录的代码:

Sub Macro_1() '' Macro_1 Macro ' Change the look of a cell in all worksheets '  

    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 65535
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    Selection.Font.Bold = True
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    With Selection.Borders(xlEdgeLeft)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlMedium
    End With
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlMedium
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlMedium
    End With
    With Selection.Borders(xlEdgeRight)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlMedium
    End With
    Selection.Borders(xlInsideVertical).LineStyle = xlNone
    Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
End Sub

3 个答案:

答案 0 :(得分:1)

为初学者尝试一下:

Option Explicit 'always use this, this helps avoiding typing mistakes in code
Sub MyRoutine()
    'declaration of variables
    Dim colIndex As Long, rowIndex As Long, ws As Worksheet
    colIndex = 13 'M column
    rowIndex = 1 'first row
    'loop through all worksheets
    For Each ws In Sheets
        ws.Cells(rowIndex, colIndex).Interior.ColorIndex = 1 'put your color here
        'do other stuff with the cell, like
        'ws.Cells(rowIndex, colIndex).Value = "some value"
    Next
End Sub

答案 1 :(得分:0)

环绕工作簿的每一页并应用颜色格式。下面是示例代码-将粗体属性设置为每张纸的第一个单元格。

For Each sh In ThisWorkbook.Sheets
    'Do your format here.
    sh.Range("$A$1").Font.Bold = True
Next

答案 2 :(得分:0)

您可以根据需要进行修改:

Option Explicit

Sub allsheets()

    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ActiveWorkbook

    For Each ws In wb.Sheets
        ws.Cells(1, 1).Value = "TEST"
    Next

End Sub