0
votes

I'm generating unique keys for invoice by using the below code and im getting Run time Error 1004 Application defined or object defined error in line

cell.Value = CStr(d & Mx) 

Why I'm getting it?

Private Sub Key_Gen()

Dim WIP_rng As Range
Dim d As String, c As Long, r As Long, s As Integer, p As Integer


Set WIP_rng = Range("WIP[Key]")

Mx = WorksheetFunction.Max(keynum)
c = 1
p = 0
    For Each col In WIP_rng
    r = col.Row
        If col.Value = "" And Cells(r, 3).Value <> "" And Cells(r, 4).Value <> "" And Cells(r, 5).Value <> "" And Cells(r, 6).Value <> "" And Cells(r, 7).Value <> "" Then
            s = Val(Len(Trim(Mx)))
            Debug.Print s
            t = 5
            p = t - s
            Debug.Print p
               If p = 1 Then
               p = "0"
               ElseIf p = 2 Then
                p = "00"
               ElseIf p = 3 Then
                p = "000"
               ElseIf p = 4 Then
                p = "0000"
                ElseIf p = 0 Then
                p = ""
               End If
                Mx = CStr(Mx + c)
                d = CStr("MG" & p)
                d = d & Mx
                col.Value = d
        c = c + 1
        End If
    Next

Application.ScreenUpdating = True

End Sub
2
How are we supposed to know? What are the values d and Mx?SJR
d will be in pattern "MG000" and Mx will be Long. Invoice no will be like MG00981Linga
There's a lot of undeclared variables in your code. I've not seen a range referenced as "WIP[Key]" before - is that valid? What is the value of Num_Key? c, r, l and s should be Long I take it?Darren Bartrup-Cook
I didn't ask what they will be, but what they ARE. When it errors what are their values?SJR
Please refer the attached updated code..Linga

2 Answers

0
votes

Write Option Explicit on top. Then declare all the variables.

Eg. Dim d as String. It would work.

Or quick and dirty:

cell.Value = CStr(d) & CStr(Mx)
0
votes

This worked for me.

Try changing the name of cell As Range to something like myCell As Range. Because cell is an object in VBA so you can't use that name.