考虑以下 Excel 电子表格:
我想根据单元格 A4:B7 中的值来格式化 row1:2 中的单元格。如果我更改这些值,row1:2 中的单元格应该合并、加边框、填充,并且文本颜色也应该相应改变。
如果我将格式单元格更改为以下内容:
答案1
这是一个 VBA 解决方案。它从您的表格中复制背景和字体颜色,Format
因此,如果您想要白色文本,请在该表格中使用白色文本。您可能需要调整边框设置(第 39 行和第 47 行)以及查找要使用的格式条件的位置(第 27 行 - 第 30 行)。如果您的示例是一个纯模型,与您的实际数据关系不大,则尤其如此。
Option Explicit
Sub MadeFormattedHeadings()
'Declarations
Dim ws As Worksheet
Dim headerRange As Range
Dim rangeSize As Integer
Dim rangeStart As Integer
Dim r As Long
Dim c As Integer
'Choose the worksheet to use
'(Pick one of these two methods)
Set ws = Worksheets("Sheet1") 'This uses the name on the tab seen in Excel
Set ws = Sheet1 'This uses the code name seen in VBA
With ws
'Remove previous headers
If UCase(.Range("A1").Value) = UCase(.Range("A5").Value) Then
.Rows("1:2").Delete
.Rows("1:2").Insert
End If
'Add new headers
rangeStart = 1
For r = 5 To 8 '<<<< There are other methods to iterate. This is just one option.
'Save the settings
Set headerRange = .Range("A" & r)
rangeSize = .Range("B" & r).Value
'Format the first row
With .Range(.Cells(1, rangeStart), .Cells(1, rangeStart + rangeSize - 1))
.Merge
.Value = headerRange.Value
.HorizontalAlignment = xlCenter
.Font.Color = headerRange.Font.Color
.Interior.Color = headerRange.Interior.Color
.BorderAround xlSolid, xlThin
End With
'Format the second row
With .Range(.Cells(2, rangeStart), .Cells(2, rangeStart + rangeSize - 1))
.Merge
.Value = rangeSize
.HorizontalAlignment = xlCenter
.BorderAround xlSolid, xlThin
End With
'Iterate to the next section
rangeStart = rangeStart + rangeSize
Next
End With
End Sub