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

问题描述 投票:-2回答:3

我在工作表中更改了单元格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
excel vba excel-vba
3个回答
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

0
投票

循环工作簿的每个工作表并应用颜色格式。下面是示例代码 - 将bold属性设置为每个工作表的第一个单元格。

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

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
© www.soinside.com 2019 - 2024. All rights reserved.