Consulting

Results 1 to 2 of 2

Thread: variable counter

  1. #1

    variable counter

    I try to create index(n) so that whenever the value of cell A1 is different from the value of cell B1, it is added to the variable N one

    The code I wrote:

     public n as integer
     Private Sub Worksheet_Change (ByVal Target As Range)
     If Cells (1, 1) .Value <> Cells (1, 2) .Value Then
     Cells (1, 2) .Value = Cells (1, 1) .Value
     n = n + 1
     End If
     Cells (n, 3) .Value = 10
     End Sub
    But the problem that the variable (n) gets the value in delay, and the macro runs the last command "Cells (n, 3) .Value = 10" before the variable (n) enough to get the value then i get the error because the variable (N) is still zero, how can I solve this issue ?

    when I wrote the last command "Cells (n, 3) .Value = 10" within the Conditional the macro works fine,without delay and the variable (n) get the result withount any delay:

    public n as integer
     Private Sub Worksheet_Change (ByVal Target As Range)
     If Cells (1, 1) .Value <> Cells (1, 2) .Value Then
     Cells (1, 2) .Value = Cells (1, 1) .Value
     n = n + 1
     Cells (n, 3) .Value = 10
     End If
     End Sub
    but I need to use the variable (n) Outside the Conditional, any help please?






    best reagards
    Attached Images Attached Images
    Last edited by Bob Phillips; 04-02-2015 at 09:20 AM. Reason: Added code tags

  2. #2
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
     Public n AS Integer
     Private Sub Worksheet_Change (ByVal Target As Range)
         If Cells (1, 1) .Value <> Cells (1, 2) .Value Then
             Cells (1, 2) .Value = Cells (1, 1) .Value
             n = n + 1
         End If
         If n > 0 Then Cells (n, 3) .Value = 10
     End Sub
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •