[英]Excel VBA: Insert new row in multiple sheets
我有一个用户窗体,用户在其中输入数据,然后单击“添加”按钮。 然后,VBA创建一个新行,并将来自用户的数据输入该行。 这可以正常工作,但是我也想在其他工作表中添加新行,这就是我遇到的问题。
这是我的代码:
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.
该过程与您现有的过程非常相似。
'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
使用工作表数组,这对两个工作表均有效。 您可以通过以相同方式将项目添加到数组来扩展它。 您也不需要将值存储为变量,因为对象的名称很小,您可以直接从源代码设置单元格的值。
这将为每个工作表找到最后一行,将其加1,然后从源对象中设置单元格的值。 然后循环处理数组中下一张纸的过程。
已测试:
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.