I am trying to create a UserForm to track Job applications. Once user fills in the textboxes and click save, it transfers data from textboxes to excel sheet named "Database". The following code is my Sub Save
which runs inside Save_CmdBt_Click event. When I enter my first data record and click save, everything works fine - no error. However, when I enter second data record, I get Method '_Default' of object 'Range' failed error. While debugging, it fails at .Cells(iRow, 1) = iRow - 5
line in code.
Dim sh As Worksheet
Dim iRow As Long
Set sh = ThisWorkbook.Sheets("Database") 'actual database sheet
If UserFormV2.RowNumber_Textbox.Value = "" Then 'when I debug for 2nd record
iRow = [Counta(Database!A:A)] + 1 'this line of code was executed, thus, txtbox value was "" for sure
Else
iRow = UserFormV2.RowNumber_Textbox.Value 'set to "" unless user selects one entry from listbox
End If
With sh
'.Activate
.Cells(iRow, 1) = iRow - 5 '-5 because that is first available row after Table header.
' The above code adds record number (1,2,3...) in excel table.
'.Cells(iRow, 3) = UserFormV2.CompanyName_TextBox1.Value ... my extra code
End With
I have check the following post (VBA Error Method of '_Default' if object 'range' failed when inserting into a table) but I do not have any textbox when the error triggers. Any idea or suggest how I can resolve this issue?
Edit 2 - Added Images of Excel sheet and comparison between working and non-working sub save method.
Edit 3 - Images removed. Error is in Listbox which gets updated after every save/delete calls.
Edit 4 (Solution to Problem)
If and Else statement regarding the ListBox1 was the cause of the error. Essentially, I wanted to have a dynamic ListBox and initially had conditions that only applies to second row in the table (which is the header and first row). Thus, after 2nd record/data, the ListBox would not update since it cannot due to set conditions thus resulting Method '_default' of Object 'Range' failed' error.