【发布时间】:2021-10-01 08:47:47
【问题描述】:
我有一个用 VBA 编写的 Excel 代码。我想在 Column 中找到短语 WJ 并从中选择适当的值。我使用For Each 循环执行此操作,但搜索所有 WJ 短语后循环不会停止。
Sub Calc()
Dim Sh As Worksheet
Dim Loc As Range
Dim Phrase As String
Dim OnlyNumber As String
Dim Weight As String
Dim Price As String
Dim WeightPrice As String
Dim WjSum As String
For Each Sh In ThisWorkbook.Worksheets
With Sh.UsedRange
Set Loc = .Cells.Find(What:=" WJ ")
If Not Loc Is Nothing Then
Do Until Loc Is Nothing
Phrase = Split(Loc.Value, ".21 ")(1)
OnlyNumber = Left(Phrase, Len(Phrase) - 4)
Price = Split(OnlyNumber, " ")(1)
Weight = Split(OnlyNumber, " ")(0)`
If Weight > 0 And Weight <= 10 Then
WeightPrice = 8
ElseIf Weight > 10 And Weight <= 20 Then
WeightPrice = 12
ElseIf Weight > 20 And Weight <= 40 Then
WeightPrice = 16
ElseIf Weight > 40 And Weight <= 60 Then
WeightPrice = 18
ElseIf Weight > 60 And Weight <= 80 Then
WeightPrice = 20
ElseIf Weight > 80 And Weight <= 100 Then
WeightPrice = 25
ElseIf Weight > 100 And Weight <= 300 Then
WeightPrice = 30
ElseIf Weight > 300 Then
WeightPrice = 100
End If
WjSum = Weight + Price
Range("D93").Value = WjSum
Set Loc = .FindNext(Loc)
Loop
End If
End With
Set Loc = Nothing
Next
End Sub
【问题讨论】:
-
永不停止的不是你的
For Each,而是你的Do-Loop。.FindNext将找到下一个匹配项,但如果没有找到更多值,则会在顶部重新开始 - 请参阅 docs.microsoft.com/en-us/office/vba/api/excel.range.findnext。您需要记住第一次匹配的地址,并检查下一次匹配是否与您的第一次匹配不同。