在VBA cells.replace中使用通配符

我正在写一个函数在Excel中添加前缀零组成一个IP地址的八位组:例如在172.19.1.17我想改变.19。 到.019。,.1。 到.001。,而.17到.017。

Te Cells.Teplace函数似乎不接受? 作为通配符。 另外,有没有一种方法可以表示“string结尾”,因此我可以在上面的例子中将前导零添加到最后一个八位字节中。

谢谢伊恩

Cells.Replace What:=".1?.", Replacement:=".01?.", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False 

这确实发现“10”。 “11.” “12”。 等等,但用“.01?”替代。

作为一种替代方法,你可以使用这个公式来向IP部分添加零(这看起来很糟糕,但是把所有的部分分开处理,最后把它们混合起来):

 =REPT(0,4-FIND(".",A1))&LEFT(A1,FIND(".",A1)-1)&"."& REPT(0,4-FIND("@",SUBSTITUTE(A1,".","@",2))+FIND(".",A1))&MID(A1,FIND(".",A1)+1,FIND("@",SUBSTITUTE(A1,".","@",2))-FIND(".",A1)-1)&"."& REPT(0,4-FIND("@",SUBSTITUTE(A1,".","@",3))+FIND("@",SUBSTITUTE(A1,".","@",2)))&MID(A1,FIND("@",SUBSTITUTE(A1,".","@",2))+1,FIND("@",SUBSTITUTE(A1,".","@",3))-FIND("@",SUBSTITUTE(A1,".","@",2))-1)&"."& REPT(0,3-LEN(A1)+FIND("@",SUBSTITUTE(A1,".","@",3)))&RIGHT(A1,LEN(A1)-FIND("@",SUBSTITUTE(A1,".","@",3))) 

您可以将它粘贴到B1 (假设您的IP位于列A的起始A1 ),无论换行符是什么。

示例文件: https : //www.dropbox.com/s/vun6urvukch9uvv/IPoctets.xlsx

你可以做这样的事情:

请务必将Application.UsedRangereplace为包含IP地址的实际范围

 Sub PadIP() Dim Arr As Variant Dim ipAddr As String Dim vCell As Variant Dim n As Long 'Replace ActiveSheet.UsedRange with the range containing your data ' 'If data is contained in column A and you have a column header 'Example: Range(Cells(2, 1), Cells(ActiveSheet.UsedRange.Rows.Count, 1)) For Each vCell In ActiveSheet.UsedRange Arr = Split(vCell.Value, ".") For n = 0 To UBound(Arr) If (n + 1) Mod 4 = 0 Then ipAddr = ipAddr & Right(String(3, "0") & Arr(n), 3) Else ipAddr = ipAddr & Right(String(3, "0") & Arr(n), 3) & "." End If Next vCell.Value = ipAddr ipAddr = "" Next End Sub 

我可以玩太:)?

这是我上面的评论。 这是如何find的一个例子.??. 并使之成为.0??.

我假设数据可以在工作表的任何地方。

 Sub Sample() Dim oRange As Range, aCell As Range, bCell As Range Dim ws As Worksheet Dim ExitLoop As Boolean Dim SearchString As String On Error GoTo Whoa Set ws = Worksheets("Sheet1") Set oRange = ws.Cells SearchString = ".??." Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not aCell Is Nothing Then Set bCell = aCell aCell.Value = CleanIt(aCell.Value) Do While ExitLoop = False Set aCell = oRange.FindNext(After:=aCell) If Not aCell Is Nothing Then If aCell.Address = bCell.Address Then Exit Do aCell.Value = CleanIt(aCell.Value) Else ExitLoop = True End If Loop End If Exit Sub Whoa: MsgBox Err.Description End Sub Function CleanIt(rng) Dim MyAr() As String Dim strTemp As String MyAr = Split(rng, ".") For i = LBound(MyAr) To UBound(MyAr) If Len(MyAr(i)) = 2 Then MyAr(i) = "0" & MyAr(i) End If strTemp = strTemp & "." & MyAr(i) Next i CleanIt = Mid(strTemp, 2) End Function 

截图

在这里输入图像说明

注意 :这仅仅是一个演示目的的例子。 上面的代码需要调整,以便它可以处理其他情况。