[英]Excel VBA to find and replace code
我有一个文本文件,当我导入Excel时如下所示:
但是,我一直试图将VBA代码组合在一起,以执行以下操作:
列A是控制器。 当AI列中的数字大于“ 97”时,只想删除它。 我只想保留第一行的“ 1”。 对于出现的每个“ 2”,我首先要复制ColB中“ 2”行中的值,然后将其粘贴到每个“ 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
首先,尝试在同一循环中执行所有操作。 您可以节省时间。 例如,您可以将前三十行替换为:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.