VBA 代码填充单元格增量为 0.1

VBA Code fill cells with increment of 0.1

我想用从 0 到范围 ("b1") 中设置的值的值填充 A 列,增量为 0.1。我有下面的代码,但是当我 运行 它时,它不会停在我在范围 ("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

尝试在比较过程中转换数字。

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

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

你可以"transpose"将整个问题转化为整数,然后将它们除以 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