gpt4 book ai didi

excel - 设置固定范围的单元格的背景颜色

转载 作者:行者123 更新时间:2023-12-02 18:56:52 26 4
gpt4 key购买 nike

我的 Excel 电子表格中有 VBA 代码。它用于根据单元格中的值设置单元格的字体和背景颜色。我在 VBA 中而不是“条件格式”中执行此操作,因为我有超过 3 个条件。代码是:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range, d As Range, fc As Long, bc As Long, bf As Boolean
Set d = Intersect(Range("A:K"), Target)
If d Is Nothing Then Exit Sub
For Each c In d
If c >= Date And c <= Date + 5 Then
fc = 2: fb = True: bc = 3
Else
Select Case c
Case "ABC"
fc = 2: fb = True: bc = 5
Case 1, 3, 5, 7
fc = 2: fb = True: bc = 1
Case "D", "E", "F"
fc = 2: fb = True: bc = 10
Case "1/1/2009"
fc = 2: fb = True: bc = 45
Case "Long string"
fc = 3: fb = True: bc = 1
Case Else
fc = 1: fb = False: bc = xlNone
End Select
End If
c.Font.ColorIndex = fc
c.Font.Bold = fb
c.Interior.ColorIndex = bc
c.Range("A1:D1").Interior.ColorIndex = bc
Next
End Sub

问题出在“c.Range”行。它始终使用当前单元格作为“A”,然后向右移动四个单元格。我希望它从当前行的“真实”单元格“A”开始,并转到当前行的“真实”单元格“D”。基本上,我想要一个固定的范围,而不是动态的范围。

最佳答案

因此c.Range("A1:D1")有自己的相对范围。
一种解决方案是使用工作表的 range 属性。
我在顶部添加了两行 (#added),并在底部更改了一行 (#changed)。

Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range, d As Range, fc As Long, bc As Long, bf As Boolean
Dim ws As Worksheet ''#added

Set d = Intersect(Range("A:K"), Target).Cells
Set ws = d.Worksheet ''#added
If d Is Nothing Then Exit Sub
For Each c In d.Cells
If c >= Date And c <= Date + 5 Then
fc = 2: bf = True: bc = 3
Else
Select Case c.Value
Case "ABC"
fc = 2: bf = True: bc = 5
Case 1, 3, 5, 7
fc = 2: bf = True: bc = 1
Case "D", "E", "F"
fc = 2: bf = True: bc = 10
Case "1/1/2009"
fc = 2: bf = True: bc = 45
Case "Long string"
fc = 3: bf = True: bc = 1
Case Else
fc = 1: bf = False: bc = xlNone
End Select
End If
c.Font.ColorIndex = fc
c.Font.Bold = bf
c.Interior.ColorIndex = bc
ws.Cells(c.Row, 1).Interior.ColorIndex = bc ''#changed
ws.Cells(c.Row, 2).Interior.ColorIndex = bc ''#added
ws.Cells(c.Row, 3).Interior.ColorIndex = bc ''#added
ws.Cells(c.Row, 4).Interior.ColorIndex = bc ''#added
Next
End Sub

关于excel - 设置固定范围的单元格的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2746185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com