![](/img/trans.png)
[英]VBA excel : Copy Entire Row and paste above multiple times based on specific cell value. Then perform same task for next rows below
[英]Excel VBA - Need to loop through delete entire 3 rows above row where cell value <> 0
好的,所以我有一張excel表格,出於我每天要拉的目的,該表格的格式不正確。 默認情況下,數據以以下格式列出(從excel工作表中查看):
x1,y1,z1,i1
, ,z2,i2
, ,z3,i3
****Blank row****
****Blank row****
****Blank row****
x2,y2,z4,i4,
, ,z5,i5,
, ,z6,i6,
^above would represent the last row for demontration purposes, but the real
sheet extends up 1000s of rows
為了以更友好的格式獲取數據,我需要一個循環,該循環將從最后一行(行)開始一直到第3行(數據開始處)。 當它在第2列中找到<>到“”的行時,我希望它刪除該單元格上方的整整3行,因此最終目標是將數據格式化為這樣的格式(在excel工作表上查看):
x1,y1,z1,i1
, ,z2,i2
, ,z3,i3
x2,y2,z4,i4
, ,z5,i5
, ,z6,i6
以下是到目前為止的內容。 自然,它根本不起作用,否則我就不會在這里。 它正在刪除我的所有數據,直到第3行為止,我不知道為什么。 任何想法將不勝感激。
Sub test()
Dim currentSht As Worksheet
Dim erow
Dim i As Integer
Set currentSht = ActiveWorkbook.Sheets(1)
erow = currentSht.Cells(Rows.Count, 3).End(xlUp).Row
For i = erow To 3 Step -3
If currentSht.Cells(i, 1).Value <> " " Then
currentSht.Range(Cells(i, 1).Offset(-1), Cells(i, 1).Offset(-3)).EntireRow.Delete
End If
Next i
End Sub
這是因為您繼續測試同一行並刪除上面的3行。
比方說, i
是30,並將其解析為真,如存在第2列數據,我們刪除它上面使得目前排三排,27排,然后i
迭代-3, i
是27,它測試相同的數據並針對相同的數據再次解析為true。
所以我們需要強迫i
改變行號:
Sub test()
Dim currentSht As Worksheet
Dim erow
Dim i As Integer
Set currentSht = ActiveWorkbook.Sheets(1)
erow = currentSht.Cells(Rows.Count, 3).End(xlUp).Row
For i = erow To 3 Step -1
If Trim(currentSht.Cells(i, 1).Value) <> "" Then
currentSht.Range(Cells(i, 1).Offset(-1), Cells(i, 1).Offset(-3)).EntireRow.Delete
i = i - 3
End If
Next i
嘗試反轉IF
:
Sub test()
Dim currentSht As Worksheet
Dim erow
Dim i As Integer
Set currentSht = ActiveWorkbook.Sheets(1)
erow = currentSht.Cells(Rows.Count, 3).End(xlUp).Row
For i = erow To 3 Step -3
If currentSht.Cells(i, 1).Value = "" Then
currentSht.Range(Cells(i, 1).Offset(-1), Cells(i, 1).Offset(-3)).EntireRow.Delete
End If
Next i
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.