Search code examples
formsvbaexceluser-input

excel user form button not working


I have made a simple user form in excel VBA that has an add and a subtract button. When one is clicked, it should add one to whatever value is in the row that has the current hour in it.

for example, if its 7:35 and someone clicks add it should add 1 to the row that has 7:00 column B. When I initialize this code with a vbYesNo button and a few if statements it works, but when i use the same code in the button clicks on the user form it does not and i can not figure out why. my code is as follows:

Private Sub CommandButton1_Click()
Sheets("Front End").Unprotect ("29745")
h = Hour(Now)
    For Each c In range("B8:B20")
        If h = Hour(c) Then
            c.Offset(0, 6) = c.Offset(0, 3) + 1
            Exit For
        End If
    Next c
Sheets("Front End").Protect ("29745")
End Sub
------------------------------------------------------
Private Sub CommandButton2_Click()
Sheets("Front End").Unprotect ("29745")
h = Hour(Now)
    For Each c In range("B8:B20")
        If h = Hour(c) Then
            c.Offset(0, 6) = c.Offset(0, 3) - 1
            Exit For
        End If
    Next c
Sheets("Front End").Protect ("29745")
End Sub

can anyone help me understand what i have wrong and what i need to do to fix it?

thank you!


Solution

  • If you're trying to increment by 1 to that column here's your problem:

    c.Offset(0, 6) = c.Offset(0, 3) + 1
    

    should be

    c.Offset(0, 6) = c.Offset(0, 6) + 1 'or both 3
    

    Your offsets weren't matching. Same problem for the subtract. Unless you were trying to subtract one from the value in column 6, and place it in column 3. In which case this code should be working fine.