划分并计算分割数

时间:2015-09-19 08:01:23

标签: excel vba function excel-vba

所以我试图获得连续划分两个整数ND所需的除法数,直到余数大于或等于0.000001。我不知道自己哪里错了。

用于NDZ的数据类型是错误的还是其他?

Option Explicit
Sub Ediv()

    Dim N As Integer
    Dim D As Integer
    Dim Z As Long
    Dim intCount As Integer

  With Sheets("Functions")

        N = Cells(16, "B").Value
        D = Cells(16, "C").Value

     If D < 1 Then
     MsgBox "Divisor is less than 1 enter value greater than 1"
     Exit Sub
     Else
     End If

     intCount = 0


      Do While Z >= 0.000001
          Z = N / D
          intCount = intCount + 1
          N = Z
      Loop

Cells(16, "D").Value = intCount
End With
End Sub

1 个答案:

答案 0 :(得分:2)

有几个麻烦的地方。请参阅以下评论。

Sub Ediv()

    Dim N As Double    '<~~ Integers cannot be decimal numbers
    Dim D As Double    '<~~ ^ same ^ 
    Dim Z As Double    '<~~ ^ same ^
    Dim intCount As Long '<~~ might be a long count

    With Sheets("Functions")

        N = .Cells(16, "B").Value  '<~~ these were Cells, not .Cells so they were not explicitly children of the Functions worksheet
        D = .Cells(16, "C").Value  '<~~^ same ^

        If D < 1 Then
            MsgBox "Divisor is less than 1 enter value greater than 1"
            Exit Sub
        End If

        intCount = 0


        Z = N / D  '<~~ Z was only initialized not assigned so it was zero
        Do While Z >= 0.000001
            Z = N / D
            intCount = intCount - CBool(Z >= 0.000001)  '<~~only increment if it will go into another loop; True is -1 in VBA.
            N = Z
        Loop
        'intCount = intCount -1 'decrement by 1 if not conditionally incremented
        .Cells(16, "D").Value = intCount  '<~~ fixed parent worksheet here as well
    End With
End Sub