【问题标题】:Using For loop with the Find function in Visual Basic Macro in Excel在 Excel 的 Visual Basic 宏中使用 For 循环和 Find 函数
【发布时间】:2018-02-04 01:12:08
【问题描述】:

我试图弄清楚如何找到特定范围内的所有数字(在本例中为 1.900 和 2.100 之间)。

到目前为止,我编写的代码能够找到 1.9 和 1.999 之间的数字,但似乎无法找到 2.000 和 2.100 之间的数字。我检查了 For 循环,看看它是否正在完成,所以 Find 函数似乎有问题。

任何解决此问题的帮助将不胜感激。我已经复制了我在下面编写的代码。

Sub FindPeaks()
With Worksheets(1).Range("b1:b500")
Dim i As Double
For i = 1.9 To 2.1 Step 0.001
    Set c = .Find(i, LookIn:=xlValues)
    If Not c Is Nothing Then
        firstAddress = c.Address
        Do
            c.Offset(0, -1).Value = "Peak"
            Set c = .FindNext(c)
        Loop While Not c Is Nothing And c.Address <> firstAddress
    End If
Next i

End With
End Sub

【问题讨论】:

  • 为什么不直接遍历范围并检查值?我认为使用 Find() 查找特定数字不是一个好方法。
  • 所提供的答案将是实现您想要做的事情的更好方法,但是(FWIW)您遇到的问题是由于二进制系统中十进制值的不精确性。如果您在For 语句之后直接包含Debug.Print i 语句,您将看到将值增加0.001 的效果。
  • 感谢您的建议和其他信息!在得到帮助后,我现在已经解决了问题。

标签: excel for-loop find vba


【解决方案1】:

此答案扩展了上面的评论,以显示解决问题的更有效方法

Sub FindPeaks()

Dim SRng as Range
Set SRng = Worksheets(1).Range("b1:b500")

For each cll in SRng
     If cll.value >= 1.9 and cll.value <= 2.1 Then
          cll.Offset(0,-1) = "Peak"
     End if
Next cll

End With
End Sub

【讨论】:

  • 感谢您的回答!这非常有帮助,正是我想要做的。
【解决方案2】:

注意到解决此任务的最佳方法不是通过 VBA,而是通过工作表公式,我想到 VBA 可用于编写工作表公式。下面的代码应该比循环运行得更快。

Sub MarkPeaks()
    ' 26 Aug 2017

    Dim Rng As Range

    ' set the range to the cells where you want the result:
    Set Rng = ActiveSheet.Range("C1:C500")

    With Rng
        ' write this formula: =IF(AND($B1>=1.9, $B1<=2.1),"Peak","")
        ' RC2 specifies the second column (meaning B)
        ' in the same row as the formula
        .FormulaR1C1 = "=IF(AND(RC2>=1.9, RC2<=2.1),""Peak"","""")"
        .Copy
        .PasteSpecial xlPasteValues
        Application.CutCopyMode = False
    End With
End Sub 

【讨论】:

    猜你喜欢
    • 2017-05-29
    • 2021-02-16
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多