簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM