excelperfect
Q:我有一个工作表,我想将里面多个相同的数据进行替换,并按顺序依次编号,如何使用VBA代码实现?例如下图1的列B中有多个“完美Excel”,使用VBA代码将其替换为“excelperfect”并加上数字编号,即“excelperfect1”、“excelperfect2”、“excelperfect3”……等。
图1
A:使用Find方法和FindNext方法进行连续查找,将找到的数据进行替换并加上计数器当前的数字。代码如下:
Sub ReplaceAndAddNum()
Dim rngLastCell As Range
Dim rngFoundCell As Range
Dim strFirstAddress As String
Dim lngCount As Long
On Error Resume Next
With ActiveSheet.UsedRange
Set rngLastCell = .Cells(.Cells.Count)
Set rngFoundCell = .Find(What:="完美Excel",_
After:=rngLastCell, _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext)
If Not rngFoundCell Is Nothing Then
strFirstAddress = rngFoundCell.Address
lngCount = 1
rngFoundCell.Value = "excelperfect" & lngCount
Do
Set rngFoundCell = .FindNext(rngFoundCell)
lngCount = lngCount + 1
rngFoundCell.Value = "excelperfect" & lngCount
Loop Until rngFoundCell.Address = strFirstAddress
EndIf
End With
End Sub
或者,使用下面更简洁的代码:
Sub ReplaceAndAddNumPlus()
Dim lngCount As Long
On Error Resume Next
lngCount= 1
Do
Cells.Find("完美Excel")= "excelperfect" & lngCount
lngCount = lngCount + 1
Loop Until Err.Number <> 0
End Sub
还有其他的方法,有兴趣的朋友可以自已尝试一下。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有