在图片中,您可以看到我的Excel工作表:
使用CommandButton(红色圆圈),我可以在表格中添加新行(蓝色圆圈)。表的范围是N到BI。
在我添加新行后,我想要我的代码,他向左跳过一个单元格,并在此列中找到第一个值" MFG" (绿线和圆圈)。在那之后,我希望他复制" MFG1"的颜色,它从......" MFG"并将其添加到新行。
我不知道该怎么做。希望有人可以帮助我。
到目前为止,这是我的代码:
Sub CommandButton1_Click()
Dim rng As Range
Dim rng2 As Range
Dim lastrow As Long
Dim year As String
Dim month As String
Dim faa As Integer
Dim faa1 As Integer
Dim faa2 As Integer
Dim faa3 As Integer
Dim AGA As Integer
Dim AGA1 As Integer
lastrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Set rng = ActiveSheet.Range("N1:BI1").Find(What:=year, LookAt:=xlWhole, SearchDirection:=xlPrevious)
If Not rng Is Nothing Then
Set rng2 = ActiveSheet.Range(Cells(lastrow, rng.Column), Cells(2, rng.Column + 11)).Find(What:=month, LookAt:=xlWhole, SearchDirection:=xlPrevious)
If Not rng2 Is Nothing Then
' Add the new rows to the table
ActiveSheet.Cells(lastrow, rng2.Column).Value = "DEL"
If IsEmpty(ActiveSheet.Range("N" & lastrow)) Then
faa = ActiveSheet.Cells(lastrow, rng2.Column).Find(What:="DEL", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column - 1
ActiveSheet.Cells(lastrow, faa).Value = "FAA"
End If
If IsEmpty(ActiveSheet.Range("N" & lastrow)) Then
faa3 = ActiveSheet.Cells(lastrow, rng2.Column).Find(What:="DEL", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column - 2
ActiveSheet.Cells(lastrow, faa3).Value = "FAA3"
End If
If IsEmpty(ActiveSheet.Range("N" & lastrow)) Then
faa2 = ActiveSheet.Cells(lastrow, rng2.Column).Find(What:="DEL", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column - 3
ActiveSheet.Cells(lastrow, faa2).Value = "FAA2"
End If
If IsEmpty(ActiveSheet.Range("N" & lastrow)) Then
faa1 = ActiveSheet.Cells(lastrow, rng2.Column).Find(What:="DEL", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column - 4
ActiveSheet.Cells(lastrow, faa1).Value = "FAA1"
End If
If IsEmpty(ActiveSheet.Range("N" & lastrow)) Then
AGA = ActiveSheet.Cells(lastrow, rng2.Column).Find(What:="DEL", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column - 5
ActiveSheet.Cells(lastrow, AGA).Value = "AGA"
End If
If IsEmpty(ActiveSheet.Range("N" & lastrow)) Then
AGA1 = ActiveSheet.Cells(lastrow, rng2.Column).Find(What:="DEL", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column - 6
ActiveSheet.Cells(lastrow, AGA1).Value = "AGA1"
End If
End If
End If
' Jumps to the left and select cell
ActiveSheet.Cells(lastrow, AGA1).Select
ActiveCell.Offset(0, -1).Select
' Here i need to find the Value "MFG" in the column and copy the color.
End Sub
我是VBA的新手,所以我的代码可能看起来不太好。
答案 0 :(得分:0)
插入行时,将最后插入的行存储在变量
中lastInsertedRow
然后搜索第一个MFG的行
rowIdx = Columns(19).Find(What:="MFG", LookAt:=xlWhole, MatchCase:=False).Row
从左侧复制颜色
colorToCopy = Range("R" & rowIdx).Interior.Color
设置插入行的颜色:
Range("T" & lastInsertedRow & ":" & "Z" & lastInsertedRow).Interior.Color = colorToCopy
为了简单起见,我使用了绝对引用。