我在VBA中创建了一个将数据发送到表的表单。表格所在的整个Excel工作表都有橙色背景,但是表格没有背景,因为我希望表格具有其默认格式,该格式已经有背景,如您所见:
。 如果我在表中添加了一条包含信息的新行,它将增加一行,但是如果我想擦除该行并调整表的大小,那么该行现在将没有背景。表格既不包含默认背景,也不包含我想要的工作表橙色背景。
我想编写代码:
interior.colorindex
与45不同,则使工作表中的所有单元格都具有那个背景interior.colorindex = 0
。 。
Dim irowoffset As Long: irowoffset = Hoja2.Range("table2").Rows.Count
Dim belowtable2 As Range
belowtable2 = Hoja2.Range("table2").Offset("irowoffset")
Dim cell As Range
For Each cell In belowtable2
If cell.Interior.ColorIndex <> 45 Then
Hoja2.Cells.Interior.ColorIndex = 45
Hoja2.Range("table2").Interior.ColorIndex = 0
End If
Next cell
答案 0 :(得分:0)
好吧,将此代码放入工作表模块。 即使在所有单元中运行似乎效率不高,它也能很好地工作。
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim irowoffset As Long
Dim belowtable2 As Range
Dim cell As Range
With Worksheets(1)
irowoffset = .Range("table2").Rows.Count
Set belowtable2 = .Range("table2").Offset(irowoffset)
For Each cell In belowtable2
If cell.Interior.ColorIndex <> 45 Then
.Cells.Interior.ColorIndex = 45
.Range("table2").Interior.ColorIndex = 0
End If
Next cell
End With
End Sub
您可能需要将工作表更改为其他内容(我在工作簿中选择了第一个工作表,最好按名称指定它)。
我认为Hoja2是一个工作表。
https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.change
https://www.contextures.com/xlvba01.html
编辑:
此代码似乎更好:
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim belowTable As Range
Dim belowTableAll As Range
With Worksheets(1)
Set belowTable = .Range("table2").Resize(1, .Range("table2").Columns.Count).Offset(.Range("table2").Rows.Count, 0)
Set belowTableAll = .Range(belowTable, .Cells(.Rows.Count, 1))
belowTableAll.Interior.ColorIndex = 45
.Range("table2").Interior.ColorIndex = 0
End With
End Sub