-1

Ok I have a worksheet "Goal 0" that with some ranges, make some calculations like...

(in A1)

=SUM(G2:G68)*I17

Then if I add/modify any of the values in 62-G68, the cell is auto calculated (numbers that are mainly negative and some possitive).

The objetive is: According to the sum of the range, find the value of I17 where the result of A1 is equal or more than 0. (Starting from 0, incrementing it 1 by 1, decimals not needed)

Manually I can add change i17 untill it reaches the goal. How ever I want to make it automatically, so if a value in the range of G2 to G68 changes it recalculate the value of I17, untill (A1 calculation gets value equal or higher than 0) but if already is higger or equal than 0 then do nothing.

Hope I explain it well

EDIT: Now I created this code ...

Function IncreaseTheValue()
    If Range("A1") < 0 Then
        Range("I17").Value = 0

        Do While Range("A1").Value < 0
            Range("I17").Value = Range("I17").Value + 1
        Loop
    End If
End Function

And works perfect, how ever it does not fires when I make a chage. How do I do that...

I try adding this in A2 cell but did not worked ...

=IF(A1 < 0, IncreaseTheValue(), "")

Regards

4

1 回答 1

1

你真的不应该这样做Function; 正如您所注意到的那样,它是不充分的,而且也不恰当地使用FunctionaSub或事件处理程序更合适的地方。

根据您的要求,将代码放入Worksheet_Change事件处理程序中。您需要对其进行微调,使其仅在 range 发生更改时触发G2:G68

试试这个(未经测试):

Private Sub Worksheet_Change(ByVal Target as Range)
Application.EnableEvents = False
If Not Intersect(Target, Range("G2:G68")) Is Nothing Then
    If Range("A1") < 0 Then
        Range("I17").Value = 0
        Do While Range("A1").Value < 0
            Range("I17").Value = Range("I17").Value + 1
        Loop
    End If
End If
Application.EnableEvents = True
End Sub

根据 pnuts 评论更新。下面的此方法将在任何单元格更改时触发宏 - 这可能是矫枉过正,或者如果 G2:G68 是根据其他单元格的更改而更改的公式,则可能有必要。任何一种方法都可以进行微调,以更好地满足您的确切需求。

Private Sub Worksheet_Change(ByVal Target as Range)
Application.EnableEvents = False
    If Range("A1") < 0 Then
        Range("I17").Value = 0
        Do While Range("A1").Value < 0
            Range("I17").Value = Range("I17").Value + 1
        Loop
    End If
Application.EnableEvents = True
End Sub
于 2013-08-20T12:20:51.633 回答