简体   繁体   中英

Transfer data from from one sheet to another based on combobox value in excel

I have 2 sheets and a userform in my workbook.

Sheet1,has 3 rows which contains shift type info.(A2=A,A3=B and A4=C),I also have additional data in col B (start time),col C (end Time) and so on..

I use a form to enter employee names(txtName) and their shift type(cboShift) in sheet 2. col A= name and col B=shift type) now i want when i complete the employee data in shift 2,by clicking UPDATE button their relevant shift info(start time,end time...) from sheet 1 copied into next cells.

 Private Sub cmdUpdate_Click()

    Dim LastRow As Long
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim rng As Range
    Dim rgnSearch As Range
    Dim rngFound As Range

    Set ws1 = Sheets("Sheet1")
    Set ws2 = Sheets("Sheet2")

    LastRow = ws2.Range("A" & ws2.Rows2.Count).End(xlUp).row + 1
    ws2.Range("A" & LastRow).Value = Me.txtName.Text
    ws1.Range("A" & LastRow).Offset(0, 1).Value = Me.cboShift.Text

    Set rgnSearch = ws1.Range("A1", ws1.Cells(Rows2.Count, 1).End(xlUp))

    With rgnSearch
        Set rngFound = .Find(Me.txtName.Text, LookIn:=xlValues)
        If Not rngFound Is Nothing Then
            ws1.Range("C" & rngFound.row & ":F" & rngFound.row).Copy Destination:=ws2.Range("C" & LastRow)
        End If
    End With
End Sub
End Sub

I have header in both sheets.

When i run the code i get error "method or data member not found).

LastRow = ws2.Range("A" & ws2.**Rows2**.Count).End(xlUp).row + 1

My next question is: is there any way to transfer data for each person when i click ADD Button instead of doing it after for all Thanx

you probably meant

LastRow = ws2.Range("A" & ws2.Rows.Count).End(xlUp).row + 1

instead of

LastRow = ws2.Range("A" & ws2.Rows2.Count).End(xlUp).row + 1

The error caused already answered in @h2so4 above.

However, a few things to consider in your code:

  1. ws1.Range("A" & LastRow).Offset(0, 1).Value = Me.cboShift.Text , not sure it's the same LastRow for both ws1 ans ws2 , is it ???

  2. Once you already have a successful find, in If Not rngFound Is Nothing Then , you can use a different coding to copy the contents of cells C:F of the same row.

Instead of:

ws1.Range("C" & rngFound.row & ":F" & rngFound.row).Copy Destination:=ws2.Range("C" & LastRow)

You can use:

rngFound.Offset(, 2).Resize(1, 4).Copy Destination:=ws2.Range("C" & LastRow)

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