When I debug it, it appears to be matching the Shop Order Number correctly, but it still deletes the first row in the worksheet, which is above the table. The table headers are in row 3 the databodyrange starts in row 4.
'Delete Button code 2 Not working
Private Sub cmbDelete_Click()
If MsgBox("Are you sure?", vbYesNo + vbCritical + vbDefaultButton2, "Delete this order") = vbYes Then
Dim son As String
son = Trim(txtShopOrdNum)
Dim orderTable As ListObject
Set orderTable = Worksheets("MASTER").ListObjects("MASTER")
Dim matchRow
matchRow = Application.Match(son, orderTable.ListColumns("SHOP ORDER NUMBER").DataBodyRange, 0)
Rows(matchRow).Delete
MsgBox ("Shop Order deleted.")
Else
MsgBox "Deletion canceled."
'do nothing
End If
Dim ctrl As Variant
For Each ctrl In Controls
If TypeName(ctrl) = "TextBox" Or TypeName(ctrl) = "ComboBox" Then ctrl.Value = ""
Next ctrl
Call Main 'Progress Bar
lstMaster.List = Sheets("Master").Range("A4:DK" & Sheets("Master").Cells(Rows.Count, 1).End(xlUp).Row).Value
lblCount = lstMaster.ListCount
Debug.Print matchRow
End Sub
This code works and I'm not sure why...
'Delete Button
Private Sub cmbDelete_Click()
Dim orderTable As ListObject 'Best option for reading/writing to a worksheet with a table
Set orderTable = Worksheets("Master").ListObjects("MASTER")
Dim Shop_Order_Number As String
Shop_Order_Number = Trim(txtShopOrdNum)
Dim i As String
Dim ctrl As Variant
Dim answer As Integer
answer = MsgBox("Are you sure?", vbYesNo + vbCritical + vbDefaultButton2, "Delete this order")
If answer = vbYes Then
MsgBox ("Shop Order deleted.")
Else
MsgBox "Deletion canceled."
'do nothing
End If
With Worksheets("Master")
i = WorksheetFunction.Match(Shop_Order_Number, .Range("E:E"), 0)
If Err.Number = 0 Then
Rows(i).EntireRow.Delete
End If
End With
For Each ctrl In Controls 'The following code clears the textboxes'
If TypeName(ctrl) = "TextBox" Or TypeName(ctrl) = "ComboBox" Then ctrl.Value = ""
Next ctrl
Call Main 'Progress Bar
lstMaster.List = Sheets("Master").Range("A4:DK" & Sheets("Master").Cells(Rows.Count, 1).End(xlUp).Row).Value
lblCount = lstMaster.ListCount
Debug.Print i
End Sub
I wonder if you're not getting this because the match is not returning anything. You can't assign i if there is no match. You might be better off putting the match in an error handler. As an example:
Dim rng as Range
Dim rNum as long
Set rng = Worksheets("Master").Range("SHOPORDNO")
If Not IsError(Application.Match(son, rng, 0)) Then
rNum = Application.Match(son, rng, 0)
MsgBox rNum
Else
MsgBox "error"
End If
Please note that I'm writing this directly (not in an SDE) so there might be a typo or two.