[英]Excel VBA to insert/delete rows at end of range
我需要根據變量說明插入或刪除一些行。
Sheet1有一個數據列表。 使用sheet2格式化后,我想復制該數據,因此sheet2只是一個模板,而sheet1就像一個用戶表單。
在for循環之前,我的代碼所做的是獲取工作表1中僅包含數據的行數以及工作表2中包含數據的行數。
如果用戶向sheet1添加更多數據,那么我需要在sheet2的末尾插入更多行,如果用戶刪除sheet1中的某些行,則這些行將從sheet2中刪除。
我現在可以獲取每行的行數,因此現在可以插入或刪除多少行,但這就是我一直未解決的問題。 我將如何插入/刪除正確數量的行。 我也想在白色和灰色之間交替顯示行顏色。
我確實認為刪除一個工作表sheet2上的所有行,然后使用交替的行顏色插入在工作表sheet1中的相同數量的行可能是一個主意,但是我確實看到了有關在條件格式中使用mod的一些信息。
誰能幫忙嗎?
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim listRows As Integer, ganttRows As Integer, listRange As Range, ganttRange As Range
Dim i As Integer
Set listRange = Columns("B:B")
Set ganttRange = Worksheets("Sheet2").Columns("B:B")
listRows = Application.WorksheetFunction.CountA(listRange)
ganttRows = Application.WorksheetFunction.CountA(ganttRange)
Worksheets("Sheet2").Range("A1") = ganttRows - listRows
For i = 1 To ganttRows - listRows
'LastRowColA = Range("A65536").End(xlUp).Row
Next i
If Target.Row Mod 2 = 0 Then
Target.EntireRow.Interior.ColorIndex = 20
End If
End Sub
我沒有對此進行測試,因為我沒有示例數據,但請嘗試一下。 您可能需要更改一些單元格引用以適合您的需求。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim listRows As Integer, ganttRows As Integer, listRange As Range, ganttRange As Range
Dim wks1 As Worksheet, wks2 As Worksheet
Set wks1 = Worksheets("Sheet2")
Set wks2 = Worksheets("Sheet1")
Set listRange = Intersect(wks1.UsedRange, wks1.columns("B:B").EntireColumn)
Set ganttRange = Intersect(wks2.UsedRange, wks2.columns("B:B").EntireColumn)
listRows = listRange.Rows.count
ganttRows = ganttRange.Rows.count
If listRows > ganttRows Then 'sheet 1 has more rows, need to insert
wks1.Range(wks1.Cells(listRows - (listRows - ganttRows), 1), wks1.Cells(listRows, 1)).EntireRow.Copy
wks2.Cells(ganttRows, 1).offset(1).PasteSpecial xlPasteValues
ElseIf ganttRows > listRows 'sheet 2 has more rows need to delete
wks2.Range(wks2.Cells(ganttRows, 1), wks2.Cells(ganttRows - (ganttRows - listRows), 1)).EntireRow.Delete
End If
Dim cel As Range
'reset range because of updates
Set ganttRange = Intersect(wks2.UsedRange, wks2.columns("B:B").EntireColumn)
For Each cel In ganttRange
If cel.Row Mod 2 = 0 Then cel.EntireRow.Interior.ColorIndex = 20
Next
End Sub
更新
只要重新閱讀這行
If the user adds some more data to sheet1 then i need to insert some more rows at the end the data in sheet2 and if the user deletes some rows in sheet1 the rows are deleted from sheet2.
我的解決方案基於用戶是否在工作表底部插入/刪除行。 如果用戶在中間插入/刪除行,則最好將整個范圍從工作表1復制到已清除的工作表2上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.