【问题标题】:For Each loop dont stop in VBA对于每个循环不要在 VBA 中停止
【发布时间】: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。您需要记住第一次匹配的地址,并检查下一次匹配是否与您的第一次匹配不同。

标签: excel vba foreach


【解决方案1】:

这里是简化的代码sn-p

Sub FindAllInUsedRange()
    Dim usedRange As Range
    Set usedRange = ActiveSheet.usedRange
    Debug.Print usedRange.Address
    
    Dim firstFoundAddress As String
    Dim foundRange As Range
    Set foundRange = usedRange.Find("a")
    firstFoundAddress = foundRange.Address

    Do
        'Do something useful with foundRange
        Debug.Print foundRange.Address
        Set foundRange = usedRange.FindNext(foundRange)
    Loop While foundRange.Address <> firstFoundAddress

End Sub

编辑

源excel表格

A B
1 a
2 b
3 a
4 b
5 a
6 b

在立即窗口中产生以下结果

$A$1:$A$6

$A$3

$A$5

$A$1

【讨论】:

  • 它不起作用。这仅搜索拳头值并停止我需要在列中找到所有短语。请帮忙
  • 我再次测试它,一切对我来说都很好。
猜你喜欢
  • 1970-01-01
  • 2016-06-19
  • 2021-07-05
  • 2018-02-13
  • 2018-10-09
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
相关资源
最近更新 更多