如何将数据添加到Excel中的特定行

我想问如何使用用户Userform将数据添加到Excel电子表格的特定行中。

当我将新产品A添加到工作表中时,我希望新数据位于产品A的最后一行下方,而其他产品B和C也是如此。

当我将新数据input到现有表格中时,是否有办法对数据进行精确sorting?

我下面的代码逐行添加数据,无论我input什么产品,都会使表格分散并出现分散。

 Private Sub CommandButton1_Click() Dim LastRow As Object Set LastRow = Sheet1.Range("a65536").End(xlUp) LastRow.Offset(1, 0).Value = TextBox1.Text LastRow.Offset(1, 1).Value = TextBox2.Text LastRow.Offset(1, 2).Value = TextBox3.Text MsgBox "One record written to Sheet1" If MsgBox("Do you want to continue entering data?", vbYesNo + vbCritical, "Caution") = vbYes Then TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" Else End TextBox1.SetFocus Unload Me End If End Sub 

您可以将数据添加到最后一行,然后sorting数据。

1)要获得最后一行,请参阅此链接

2)要sorting的数据,你可以使用这个简单的代码。 下面的示例代码将sorting具有标题的Col A

 With Sheets("Sheet1") .Columns("A:A").Sort Key1:=.Range("A1"), Order1:=xlAscending, Header:=xlYes, _ OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _ DataOption1:=xlSortNormal End With 

3)关于使用End一个提示:请参阅此线程中的第6点。

4)所以,如果我结合了两个代码,那么你的代码将看起来像这样

 Option Explicit Private Sub CommandButton1_Click() Dim LastRow As Long '~~> Change this to the releavnt sheet name With Sheets("Sheet1") LastRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1 .Range("A" & LastRow) = TextBox1.Text .Range("B" & LastRow) = TextBox2.Text .Range("C" & LastRow) = TextBox3.Text '~~> Sort the Data. I am assuming that Row 1 has Headers .Columns("A:C").Sort Key1:=.Range("A2"), Order1:=xlAscending, Header:=xlYes, _ OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _ DataOption1:=xlSortNormal End With If MsgBox("One record written to Sheet1. Do you want to continue entering data?", vbYesNo + vbCritical, "Caution") = vbYes Then TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" TextBox1.SetFocus Else Unload Me End If End Sub