自动在其他工作表Excel中插入行如果添加了行

时间:2018-10-05 04:57:36

标签: excel excel-vba

我在Sheet1中有一个Excel表CustomerTable,在Sheet2中有一个SalesTable。 现在,CustomerTable具有“ Customer_Code”列(Col A),公式如下: =[@[CustomerName ]] & [@[No order ]]

现在我要实现的是每次在CustomerTable中添加新行时,CustomerTable的Col A中Customer_Code的新记录也出现在SalesTable中。

非常像这样: CustomerTable的Col A中的MA18209出现在SalesTable的Customer_Code col(Col B)的最后一行。

这是我当前在Sheet1中输入的代码:

  Sub CopyCustomerCode()
    Dim A As String
    Dim ws As Worksheet
    Set ws = Sheets("Sheet2")

    Dim otherRow As Long
    otherRow = ws.Range("B" & Rows.Count).End(xlUp).Row + 1

    ws.Cells(otherRow, 1).Value = b

 End Sub

它什么都不做。那么我该怎么做才能修改上面的代码?对于Excel,理想的状态是自动复制Col A中的值,而不是通过单击宏按钮。

1 个答案:

答案 0 :(得分:1)

如何在CustomerTable中添加行?通过在表格顶部插入新行?还是通过在底部写新信息并让excel格式作为新行?

您可以编写一个宏,以便一次在CustomerTable和SalesTable中创建新行。由于某种原因,我喜欢最新的条目位于表格的顶部,因此我总是使按钮在第2行中插入新的Rowo。

此代码将在click_event上向SalesTable添加新行(如果您的表格格式设置为表格)。如果您想完全避免单击,可以尝试使用worksheet_change事件。

 Sub CopyCustomerCode()

    Dim ws As Worksheet
    Dim ws As Worksheet
    Dim newRow As ListRow
    Dim SalesTable As ListObject

    Set ws1 = Sheets("Sheet1")
    Set ws2 = Sheets("Sheet2")
                                    'your table name here
    Set SalesTable = ws2.ListObjects("Sales_Table")

    'lines for determining last rows
    With SalesTable.Range
        LastRow  .Rows(.Rows.Count).Row
    End With

    'add new row to bottom of the table
     Set newRow = SalesTable.ListRow.Add

     'copy info from column A in CustomerTable to SalesTable
     With newRow
                              'if inserted row is row 2
         .Range(2) = ws1.Range("A2").Value
     End With

 End Sub

在第2行中为CustomerTable插入新行的代码

Sub New_Row2()

Dim ws1 As Worksheet

Set ws1 = Sheets("Sheet1")

With ws1.Range("A2")
     .EntireRow.Insert Shift:xlDown, CopyOrigin:xlFormatFromRightOrBelow
     End With

End Sub

编辑:如果在表的底部添加了CutomerTable中的新条目,则可以尝试查找CustomerTable的最后一行并在.Range(2)行中使用它。

代码应如下所示(您必须将其添加到button_click过程中):

Sub CopyCustomerCode()

        Dim ws As Worksheet
        Dim ws As Worksheet
        Dim newRow As ListRow
        Dim CustomerTable As ListObject
        Dim SalesTable As ListObject

        Set ws1 = Sheets("Sheet1")
        Set ws2 = Sheets("Sheet2")
                                        'your table name here
        Set SalesTable = ws2.ListObjects("Sales_Table")
                                            'your table name here
        Set CustomerTable = ws1.ListObjects("Cutomer Table")

        'lines for determining last rows
        With SalesTable.Range
            LastRow = .Rows(.Rows.Count).Row
        End With 
        With CustomerTable.Range
             LastCusRow = .Rows(.Rows.Count).Row
        End With     

        'add new row to bottom of the table
         Set newRow = SalesTable.ListRow.Add

         'copy info from column A in CustomerTable to SalesTable
         With newRow
             .Range(2) = ws1.Cells(LastCusRow, "A").Value
         End With

     End Sub