I'm trying to insert a new row below the headers, to insert the data of the Userform.
My current code adds the new data in row 4, but it isn't adding a new row in row 4. It is overwriting the data that was in row 4.
Private Sub KnopOpslaan_Click()
Dim ws As Worksheet
Set ws = Worksheets("Data")
'Regel invoegen op rij 4.
If Range("a4") <> "" Then
Rows("4:4").Select
Selection.Insert shift:=xlDown
End If
'Formulier doorzetten naar het excel bestand.
ws.Cells(4, 1).Value = VoorraadOpnameTA.Datumbox.Value
ws.Cells(4, 2).Value = VoorraadOpnameTA.Tijdbox.Value
ws.Cells(4, 3).Value = VoorraadOpnameTA.Opnemer.Value
End Sub
Problem in Selection.Insert shift:=xlDown
this line. Replace the line with
Selection.Insert shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
This is full code.
Dim ws As Worksheet
Set ws = Worksheets("Data")
'Regel invoegen op rij 4.
If Range("a4") <> "" Then
Rows("4:4").Select
Selection.Insert shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
'Formulier doorzetten naar het excel bestand.
ws.Cells(4, 1).Value = VoorraadOpnameTA.Datumbox.Value
ws.Cells(4, 2).Value = VoorraadOpnameTA.Tijdbox.Value
ws.Cells(4, 3).Value = VoorraadOpnameTA.Opnemer.Value
End If
You have Hard-Coded you Row number while writing data to Row 4. So its updating values always into Row4. If you are actually looking at inserting Row below Row4 and writing data into Row5 then try below. Code will insert Row below Row4 and insert data to Row5 always
Private Sub KnopOpslaan_Click()
Dim ws As Worksheet
Set ws = Worksheets("Data")
'Regel invoegen op rij 4.
If Range("a4") <> "" Then
Rows("4:4").Select
Selection.Insert shift:=xlDown
End If
'Formulier doorzetten naar het excel bestand.
ws.Cells(5, 1).Value = VoorraadOpnameTA.Datumbox.Value
ws.Cells(5, 2).Value = VoorraadOpnameTA.Tijdbox.Value
ws.Cells(5, 3).Value = VoorraadOpnameTA.Opnemer.Value
End Sub
The easiest would be to format your data as a table on the worksheet, this makes it a listobject, you can then use the
ws.ListObjects("name").ListRows.Add 1
this inserts a row just below the headers, regardless of where the table is actually on the sheet.
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.