宏未按预期方式进行分割–错误的输出

时间:2019-01-06 20:45:05

标签: excel vba divide

我有一个宏,它没有产生应有的输出。在下面的示例Excel工作表中,该代码将D30中的单元格数量平均分为10个不同的单元格,直到12.00之后达到12.00,多余的数量将使用单元格B30中两个单元格的第一个数字转到该单元格(在此示例中为1)。在JPEG示例中给出了正确的输出。在下面的样本表中,查看预期结果以查看当前输出正在产生什么。

单击here获得Excel图像。

Sub DIVIDE()
Application.ScreenUpdating = False

Dim pair As Variant, accumulator As Variant
Dim findFifteen As Double
Dim remainder As Long, found As Long

found = 1

For Each pair In Range("B30, F30, J30")
If Right(pair, 2) = 15 Then
    If pair.Offset(0, 2) <= 12 Then
        findFifteen = pair.Offset(0, 2) / 10
        remainder = 0
    Else
        findFifteen = 1
        remainder = pair.Offset(0, 2) Mod 10
    End If

    For Each accumulator In Range("A36, D36, G36, J36, M36, A40, D40, G40, J40, M40")
        If accumulator.Offset(-1, 0) = Val(Left(pair, InStr(pair, "-") - 1)) Then
            accumulator.Value = accumulator.Value + remainder
        End If
        accumulator.Value = accumulator.Value + findFifteen
    Next accumulator
    End If
Next pair

Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:1)

我不知道您的代码做什么,但是请尝试以下操作。它给了我您期望的输出。

Option Explicit

Sub DivideSomeStuff()

    Dim pair As Range, accumulator As Range
    Dim findFifteen As Double
    Dim remainder As Long

    For Each pair In Range("B30, F30, J30")
        If Right(pair, 2) = 15 Then
            If pair.Offset(0, 2) <= 12 Then
                remainder = 0
            Else
                remainder = pair.Offset(0, 2) Mod 12
            End If

            findFifteen = (pair.Offset(0, 2) - remainder) / 10

            For Each accumulator In Range("A36, D36, G36, J36, M36, A40, D40, G40, J40, M40")
                If accumulator.Offset(-1, 0) = Val(Left(pair, InStr(pair, "-") - 1)) Then
                    accumulator.Value = accumulator.Value + remainder
                End If
                accumulator.Value = accumulator.Value + findFifteen
            Next accumulator
        End If
    Next pair

End Sub

您可能应该用单元格D30中的其他值进行测试,以查看输出是否仍然正确/符合预期。


我仍然不知道您的代码做什么,但是如果您将工作表上的单元格B30F30J30更改为以7结尾(例如,诸如{ {1}},然后将"1-7"更改为相同的值(在本例中为7),那么我认为下面的代码将提供预期的输出。

NUMBER_TO_CHANGE

Code's output