我不会使用 VBA 来解决这个问题。我会输入:
=IF(AND(LEFT(B2,1)="F",B2<>"Fruits"),B2,A1)
放入 A2 并向下复制。这似乎达到了您所寻求的效果。
如果你真的想用VBA,测试的代码是:
Dim CellValue As String
Dim RowCrnt As Integer
Dim RowMax As Integer
With Sheets("Sheet1") ' Replace Sheet1 by the name of your sheet
RowMax = .Cells(Rows.Count, "B").End(xlUp).Row
For RowCrnt = 2 To RowMax
CellValue = .Cells(RowCrnt, 2).Value
If Left(CellValue, 1) = "F" And CellValue <> "Fruits" Then
.Cells(RowCrnt, 1).Value = CellValue
Else
.Cells(RowCrnt, 1).Value = .Cells(RowCrnt - 1, 1).Value
End If
Next
End With
以下内容解释了上述代码中新手可能难以理解的那些方面。
宏记录器几乎总是使用 Range("A5") 或 Range("A5:C10") 来引用范围。
似乎有一些命令(抱歉,不记得是哪个)必须使用这种格式,但对于大多数用途而言,Cells(Row, Column) 更方便。
如果您想为工作表“Sheet1”的“A5:C10”范围内的每个数值加 1,下面显示了如何使用单元格执行此操作:
Dim CellValue as String
Dim ColCrnt As Integer
Dim RowCrnt As Integer
With Sheets("Sheet1")
For RowCrnt = 5 to 10
For ColCrnt = 1 to 3 ' "A" to "C"
CellValue = .Cells(RowCrnt, ColCrnt).Value
If IsNumeric(CellValue) Then
.Cells(RowCrnt, ColCrnt).Value = CellValue + 1
End If
Next
Next
End With
访问工作表中的单元格会花费时间,但我更多地使用了 CellValue,因为代码可能会因为单元格引用过多而变得非常混乱。
注意:在“A5”中,列在前,但在 Cells(5,1) 中,行在前。
您可以使用单元格定义范围。以下将活动工作表的“A5:C10”设置为粗体:
Range(Cells(5,1), Cells(10,3)).Font.Bold = True
要寻址活动工作表最后一行的 A 列:
Cells(Rows.Count,"A")
要寻址第 1 行的最后一列:
Cells(1,Columns.Count)
Ctrl+Up、Ctrl+Down、Ctrl+Left 和 Ctrl+Right 可用于从空单元格跳转到具有指定方向值的下一个单元格。您可以在 VBA 中执行相同的操作。但更有用的是,您可以获得光标将跳转到的行或列的值,而不会因移动光标而造成时间损失。
如果光标位于最后一行的 B 列并且您按了 Ctrl+Up,则光标将跳转到 B 列中具有值的最后一行。以下将 RowMax 设置为活动工作表的该行号:
RowMax = Cells(Rows.Count, "B").End(xlUp).Row
获取第 27 行最后使用的列:
ColMax = Cells(27,Columns.Count).End(xlToRight).Column