我正在尝试找到一个值“PLGDY”,从此行复制数据,在找到的一行上方插入一个新行,将数据粘贴到新行中,将值“PLGDY”替换为“PLGDN”。
我写了一个宏,它不是将数据复制到新行,而是粘贴到右边的单元格中。它还将两行中的值更改为“PLGDN”。
我想使用For Next循环,因为我有很多值要改变。是否可以检查要更改的值数量?我想用这个号码作为反击。
Sub Find_and_Change()
'
'Find a "PLGDY" and set an active cell
Cells.Find(What:="PLGDY", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
'select a block of data in a row
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlToLeft)).Select
'copy selected block of data
Selection.Copy
'insert a row above active cell
ActiveSheet.Cells(ActiveCell.Row, 1).Select
ActiveCell.EntireRow.Insert
'set an active cell at the beginig of a row and move into column A
ActiveSheet.Cells(ActiveCell.Row, 1).Select
' paste copied data into this cell
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Now I select whole row
ActiveCell.EntireRow.Select
'I need to replace PLGDY with PLGDN in this row
Selection.Replace What:="PLGDY", Replacement:="PLGDN", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'I need to move active cell 10 columns right and one row down because I want to find next PLGDY
ActiveCell.Offset(1, 10).Select
End Sub
答案 0 :(得分:1)
mrbungle'答案就在眼前!效果很好。
对于任何发现此问题且打算使用此代码复制具有多个值的行的人,都需要进行一次调整。
我能够复制/粘贴循环并更改变量以适应,只有异常才需要在ActiveCell.EntireRow.Select
之后添加ActiveCell.EntireRow.Insert
,否则当第二个循环通过新值替换原始值时未选择值以及新行。为我的目的更新的代码是:
Private Sub LT2V()
Dim vCount As Integer
'Add Lesser tier of 2V
vCount = Application.WorksheetFunction.CountIf(Range("D:D"), "2V")
Do Until vCount = 0
Cells.Find(What:="2V", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
ActiveCell.EntireRow.Copy
ActiveCell.EntireRow.Insert
ActiveCell.EntireRow.Select
Selection.Replace What:="2V", Replacement:="1V", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
ActiveCell.Offset(1, 10).Select
vCount = vCount - 1
Loop
End Sub
答案 1 :(得分:0)
你是新人我明白你可能不知道所有的快捷方式和内置功能。我一直都在学习新的东西。在这种情况下,我使用内置的工作表函数CountIf
来获取值出现的次数。然后循环我喜欢使用Do Until Loop
并在每个循环中减去1直到我达到0。
Sub Find_and_Change()
vCount = Application.WorksheetFunction.CountIf(Range("A1:Z100"), "PLGDY")
Do Until vCount = 0
Cells.Find(What:="PLGDY", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
ActiveCell.EntireRow.Copy
ActiveCell.EntireRow.Insert
Selection.Replace What:="PLGDY", Replacement:="PLGDN", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
ActiveCell.Offset(1, 10).Select
vCount = vCount - 1
Loop
End Sub