简体   繁体   English

Excel VBA用户表单。 将数据添加到标题下方的新行中

[英]Excel VBA userform. Add data into a new row, below headers

I'm trying to insert a new row below the headers, to insert the data of the Userform. 我正在尝试在标题下方插入新行,以插入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. 我当前的代码在第4行中添加了新数据,但没有在第4行中添加新行。它正在覆盖第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. Selection.Insert shift:=xlDown问题, Selection.Insert shift:=xlDown此行。 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. 在将数据写入第4行时,您已经对行号进行了硬编码。因此,其更新值总是在第4行中。 If you are actually looking at inserting Row below Row4 and writing data into Row5 then try below. 如果您实际上是在将Row插入Row4并将数据写入Row5,请尝试以下操作。 Code will insert Row below Row4 and insert data to Row5 always 代码将在第4行下方插入行,并始终将数据插入第5行

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. 无论表格实际在表中的什么位置,这都会在标题下方插入一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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