简体   繁体   中英

Need assistance with Excel, VBA and userforms, specifically over writing existing data

I'm currently developing a data input system at my place of work, utilising userforms for ease of input and have got a bit stuck on some of the coding. I want it to check if the reference number inserted into the form is in the data already saved, and if not add the data as a new row. I've managed this aspect but am stuck on the next part - over writing the existing data if the reference number is present. My code so far is

Sub savebutton_click ()

Dim emptyrow As Long
Dim r as Excel.Range

Set r = sheets("data").range("a:a").find(what:=Auditref.Text.LookAt:=xlPart, MatchCase:= True)

If r Is Nothing then
    emptyrow = WorksheetFunction.CountA(range("a:a")) + 1
    Cells(emptyrow, 1).value = auditref.value
    Cells(emptyrow, 2).value = datereview. Value
Else
    k = Auditref.Value
    Cells(kRow, 2).value = datereview.value
End if

End sub 

It is raising an error at the cells(kRow, 2) point and I am lost as to how to sort this.

Any ideas?

Something like this will work:

Dim sht as worksheet, r as range

set sht = sheets("data")
Set r = sht.range("a:a").find(what:=Auditref.Text, _
                              LookAt:=xlPart, MatchCase:= True)

If r Is Nothing then set r = sht.cells(sht.rows.count, 1).end(xlup).offset(1, 0)
with r.entirerow
    .cells(1).value = auditref.value
    .Cells(2).value = datereview.value
end with

Are you sure you want xlPart in the Find() there? Seems like you'd want an exact match...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM