简体   繁体   English

Excel VBA:在多个工作表中插入新行

[英]Excel VBA: Insert new row in multiple sheets

I have a userform where the user inputs data and then clicks the button Add. 我有一个用户窗体,用户在其中输入数据,然后单击“添加”按钮。 The VBA then creates a new row and inputs the data from the user into that row. 然后,VBA创建一个新行,并将来自用户的数据输入该行。 This works fine, however I want to also add a new row in a different sheet as well and this is where I am stuck. 这可以正常工作,但是我也想在其他工作表中添加新行,这就是我遇到的问题。

This is my code: 这是我的代码:

 Dim i As String Dim j As String Dim k As String Dim m As String Dim n As String j = XIDBox.Value i = OrgNameBox.Value k = ContactNameBox.Value m = PhoneBox.Value n = EmailBox.Value dstRw = Sheets("Input Data").Range("A" & Rows.Count).End(xlUp).Row + 1 Sheets("Input Data").Cells(dstRw, 1).Value = i Sheets("Input Data").Cells(dstRw, 2).Value = j Sheets("Input Data").Cells(dstRw, 4).Value = k Sheets("Input Data").Cells(dstRw, 6).Value = m Sheets("Input Data").Cells(dstRw, 5).Value = n 'Here I want a code that inserts a blank row just as dstRw does above but in a different sheet. 

The process is very similar to what you have in place. 该过程与您现有的过程非常相似。

'Here I want a code that inserts a blank row just as dstRw does above but in a different sheet.
Dim otherSheet As Worksheet
Set otherSheet = Sheets("Other Sheet Name")

' Insert as the last row.
Dim otherRow As Long
otherRow = otherSheet.Range("A" & Rows.Count).End(xlUp).Row + 1

' Now write the values.
otherSheet.Cells(otherRow, 1).Value = i
otherSheet.Cells(otherRow, 2).Value = j
otherSheet.Cells(otherRow, 4).Value = k
otherSheet.Cells(otherRow, 6).Value = m
otherSheet.Cells(otherRow, 5).Value = n

This works for both sheets using an array for your sheets. 使用工作表数组,这对两个工作表均有效。 You can expand it by adding items to the array in the same manner. 您可以通过以相同方式将项目添加到数组来扩展它。 You also don't need to store the values as variables, since the name of the object is small, you can just set the cell's values directly from the source. 您也不需要将值存储为变量,因为对象的名称很小,您可以直接从源代码设置单元格的值。

This finds the last row for each sheet, adds 1 and then sets the values of the cells from your source objects. 这将为每个工作表找到最后一行,将其加1,然后从源对象中设置单元格的值。 Then loops the process for the next sheet in the array. 然后循环处理数组中下一张纸的过程。

TESTED: 已测试:

Sub ValueMove()

Dim dstRw As Long
Dim sheet(1) As String

    sheet(0) = "Input Data"
    sheet(1) = "Different Sheet"

    For s = 0 To 1

        dstRw = Sheets(sheet(s)).Range("A" & Rows.count).End(xlUp).row + 1

        Sheets(sheet(s)).Cells(dstRw, 1).Value = OrgNameBox.Value
        Sheets(sheet(s)).Cells(dstRw, 2).Value = XIDBox.Value
        Sheets(sheet(s)).Cells(dstRw, 4).Value = ContactNameBox.Value
        Sheets(sheet(s)).Cells(dstRw, 6).Value = PhoneBox.Value
        Sheets(sheet(s)).Cells(dstRw, 5).Value = EmailBox.Value
    Next s

End Sub

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

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