Getting error: Object variable or With block variable not set (Error 91) in excel vba.
Sub RegisterNewUser()
'Disable screen refresh during code excution
Application.ScreenUpdating = False
'Variables
Dim users As Worksheet 'Variable for users table sheet
Dim NewUser As Worksheet 'Variable for new user entry sheet
Dim RecordIsValid As String
Dim NextRecordIndex As Long 'Variable for the next available row in the users table
Set users = ThisWorkbook.Worksheets("USERS")
Set NewUser = ThisWorkbook.Worksheets("NEW USER")
NextRecordIndex = users.ListObjects("USERS").ListRows.Count
If NextRecordIndex = 0 Then
users.ListObjects("USERS").DataBodyRange(NextRecordIndex, 1).Value = NewUser.Range("D" & 6).Value
Else
NextRecordIndex = NextRecordIndex + 1
users.ListObjects("USERS").DataBodyRange(NextRecordIndex, 1).Value = NewUser.Range("D" & 6).Value
End If
Error is exactly here:
after the if statement:
users.ListObjects("USERS").DataBodyRange(NextRecordIndex, 1).Value = NewUser.Range("D" & 6).Value
The code in the else condition is working fine. It only gives this error if the USERS table is empty and the row count is zero.
Can anyone please guide what is the problem?
Thanks..