使用Range.Find和Range.FindNext来识别匹配的单元格,而不是循环遍历单元格或数组。
Sub Balance()
Worksheets("Sheet1").Activate
Dim c As Range
Dim AccountCol As Long
Dim BalanceCol As Long
Dim LastAccountRow As Range
Dim FirstFoundCell As Range
AccountCol = WorksheetFunction.Match("Account", Rows("1:1"), 0)
BalanceCol = WorksheetFunction.Match("Balance", Rows("1:1"), 0)
With Range(Cells(1, AccountCol), Cells(Cells(Rows.Count, 1).End(xlUp).Row, AccountCol))
Set c = .Find("100", .Cells(1, AccountCol), xlValues, xlPart)
If Not c Is Nothing Then
Set FirstFoundCell = c
If Left(c.Value2, 3) = "100" Then
Cells(c.Row, BalanceCol) = Cells(c.Row, BalanceCol) * 100
End If
Set c = .FindNext(c)
Do Until c.Address = FirstFoundCell.Address
If Left(c.Value2, 3) = "100" Then
Cells(c.Row, BalanceCol) = Cells(c.Row, BalanceCol) * 100
End If
Set c = .FindNext(c)
If Left(c.Value2, 3) = "100" Then
Cells(c.Row, BalanceCol) = Cells(c.Row, BalanceCol) * 100
End If
Loop
End If
End With
End Sub
这会在“账户”列中查找第一个包含“100”的单元格,确认找到的值以100开头,并将余额乘以100。然后尝试查找下一个包含“100”的单元格,直到找到的单元格与第一个找到的单元格匹配。
要引用表格,只需用结构化引用替换“Match”函数来引用表格列:
AccountCol = [Table1[Account]].Column
BalanceCol = [Table1[Balance]].Column