【问题标题】:VBA Code fill cells with increment of 0.1VBA 代码以 0.1 的增量填充单元格
【发布时间】:2018-07-21 20:34:33
【问题描述】:

我想用从 0 到 range("b1") 中设置的值填充 A 列,增量为 0.1。我有下面的代码,但是当我运行它时,它不会停止在我在 range("b1") 上设置的值上。帮忙?

Dim x As Double

Do

     x = x + 0.1

     Range("A" & Rows.count).End(xlUp).Offset(1).Value = x

Loop Until x = Range("b1").Value

【问题讨论】:

  • 永远不要使用浮点数进行相等比较。 (虽然在 inequality 比较中使用它们很好。尝试重写代码以使用 <=>= 代替。)

标签: excel vba loops increment


【解决方案1】:

您可以将整个问题“转置”为整数,然后将它们除以 10 以获得小数

Option Explicit

Sub main()
    Dim iLoop As Long
    For iLoop = 1 To Range("b1").Value * 10 + 1
         Range("A" & iLoop).Value = (iLoop - 1) * 0.1
    Next
End Sub

【讨论】:

    【解决方案2】:

    尝试在比较期间转换数字。

    Private Sub this()
        Dim i As Long, y As Double, x As Double
        x = CDbl(ThisWorkbook.Sheets("Sheet1").Range("b1").Value)
        Debug.Print ; x
        y = 0
        i = 1
        For i = 1 To 999
            ThisWorkbook.Sheets("Sheet1").Range("a" & i).Value = y
            y = y + 0.01
            Debug.Print ; y
            If CLng(y) = CLng(x) Then
                Exit For
            End If
        Next i
    End Sub
    

    Private Sub this()
        Dim i As Long, y As Double, x As Double
        x = CDbl(ThisWorkbook.Sheets("Sheet1").Range("b1").Value)
        Debug.Print ; x
        y = 0
        i = 1
        For i = 1 To 999
            ThisWorkbook.Sheets("Sheet1").Range("a" & i).Value = y
            y = y + 0.01
            Debug.Print ; y
            If CStr(y) = CStr(x) Then
                Exit For
            End If
        Next i
    End Sub
    

    【讨论】:

      【解决方案3】:

      对于 EQUALS(长十进制)数字,使用 as double 可能会有问题。如果您将循环更改为Loop Until x >= Range("b1").Value,您应该会得到理想的结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-14
        • 2018-01-26
        • 2015-06-04
        • 2013-05-11
        • 1970-01-01
        • 2021-04-20
        • 1970-01-01
        相关资源
        最近更新 更多