我有一个文本文件,当我导入Excel时,如下所示:
但是,我一直试图整理一个VBA代码,该代码将执行以下操作:
A列是控制器。 当一个数字高于" 97"出现在A列中我只想删除它。 我只想让第一排" 1' s"依然存在。 对于每一个" 2"看来,我首先想要在" 2"中复制ColB中的值。行,并将其粘贴到每个" 3"直到我打到下一个" 2"。 然后,我想删除" 2"
所以最终文件看起来应该是这样的:
到目前为止,我得到的是:
Sub Deleterow97()
'Macro to format text file to readable format for client
Last = Cells(Rows.Count, "A").End(xlUp).Row
For i = Last To 1 Step -1
If (Cells(i, "A").Value) = "97" Then
Cells(i, "A").EntireRow.Delete
End If
Next i
Last = Cells(Rows.Count, "A").End(xlUp).Row
For i = Last To 1 Step -1
If (Cells(i, "A").Value) = "98" Then
Cells(i, "A").EntireRow.Delete
End If
Next i
Last = Cells(Rows.Count, "A").End(xlUp).Row
For i = Last To 1 Step -1
If (Cells(i, "A").Value) = "99" Then
Cells(i, "A").EntireRow.Delete
End If
Next i
Last = Cells(Rows.Count, "A").End(xlUp).Row
For i = Last To 2 Step -1
If (Cells(i, "A").Value) = "1" Then
Cells(i, "A").EntireRow.Delete
End If
Next i
Dim CellValue As String
Dim RowCrnt As Integer
Dim RowMax As Integer
With Sheets("Sheet1") ' Replace Sheet1 by the name of your sheet
RowMax = .Cells(Rows.Count, "B").End(xlUp).Row
For RowCrnt = 1 To RowMax
If .Cells(RowCrnt, 1) = "2" Then
.Range("A:A").Replace What:="3", Replacement:=.Cells(RowCrnt, 2), LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End If
Next
Last = Cells(Rows.Count, "A").End(xlUp).Row
For i = Last To 2 Step -1
If (Cells(i, "A").Value) = "2" Then
Cells(i, "A").EntireRow.Delete
End If
Next i
End With
End Sub
答案 0 :(得分:0)
首先,尝试在同一循环中执行所有操作。你可以节省时间。例如,您可以用以下内容替换前30行:
Last = Cells(Rows.Count, "A").End(xlUp).Row
For i = Last To 1 Step -1
If (Cint(Cells(i, "A").Value)) >= 97 Then
Cells(i, "A").EntireRow.Delete
End If
If i >= 2 AND (Cells(i, "A").Value) = "1" Then
Cells(i, "A").EntireRow.Delete
End If
Next i
编辑:最后
Sub formatSheet()
Dim Last As Long
Dim cellToCopy As String
Last = Cells(Rows.Count, "A").End(xlUp).Row
For i = 2 To Last
'reverse loop from start to end make it easier to change all "3" below "2"
cellToCopy = ""
If (CDbl(Cells(i, "A").Value)) >= 97 And (CDbl(Cells(i, "A").Value)) <= 120 Then
' convert to double because you deal with big numbers in column B
' and fixe a limit to avoid bugs
Cells(i, "A").EntireRow.Delete
End If
If CDbl(Cells(i, "A").Value) = 1 Then
Cells(i, "A").EntireRow.Delete
End If
If CDbl(Cells(i, "A").Value) = 2 Then
cellToCopy = Cells(i, "B").Value
Cells(i, "A").EntireRow.Delete
Dim j As Long
j = i
Do While CDbl(Cells(j, "A").Value) = 3
Cells(j, "A").Value = cellToCopy
j = j + 1
Loop
End If
Next i
End Sub