VBA 循环仅搜索并替换字符串第一次出现的前两个字符

问题描述 投票:0回答:2

如果 A 列单元格中的字符串以 NL、NC 或 NX 开头,我想将其替换为字母 N,但每个字符串中仅第一次出现 NL、NC、NX,并将其粘贴到 C 列中,图像解释了最终结果,

enter image description here

    Sub Replace_NX_NC_NL()


    Dim lr As Long
    Dim LastRow As Long
    
    LastRow = Cells(Rows.Count, "A").End(xlUp).Row
    
 
    Range("C5").Select
    ActiveCell.Formula = "=SUBSTITUTE(A5, ""NC"", ""N"",1 )"
    Selection.AutoFill Destination:=Range("C5:C" & LastRow)
   
    Range("C5:C" & LastRow).Select
    Selection.Copy
    Range("C5:C" & LastRow).Select
    Selection.PasteSpecial Paste:=xlPasteValues
        
    
    End Sub

我能够启动代码来替换 NC,但下一步对我来说是个谜......有人可以帮忙吗?

excel vba
2个回答
0
投票

在 A 列上进行一个简单的循环怎么样,我们检查字符串是否以其中任何一个开头,如果是,则放入 N 并将其余的重新添加回来?

Sub Replace_NX_NC_NL()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim i As Long
    Dim originalText As String
    Dim modifiedText As String

    ' Set the worksheet to work on
    Set ws = ThisWorkbook.Sheets(1) ' Change the index or name as necessary
    
    ' Find the last row in column A
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    ' Loop through each cell in column A
    For i = 1 To lastRow
        originalText = ws.Cells(i, "A").Value
        modifiedText = originalText
        
        ' Check if the string starts with NL, NC, or NX
        If Left(originalText, 2) = "NL" Or Left(originalText, 2) = "NC" Or Left(originalText, 2) = "NX" Then
            ' Replace the first occurrence of NL, NC, or NX with N
            modifiedText = "N" & Mid(originalText, 3)
        End If
        
        ' Paste the modified text into column C
        ws.Cells(i, "C").Value = modifiedText
    Next i

End Sub

0
投票
Sub Replace_NX_NC_NL()
    Dim lr As Long, s As String
    Dim LastRow As Long
    Const KEYS = "NL,NC,NX"
    LastRow = Cells(Rows.Count, "A").End(xlUp).Row
    For lr = 5 To LastRow
        s = Left(Cells(lr, 1), 2)
        If InStr(1, KEYS, s, vbTextCompare) > 0 Then
            Cells(lr, 3) = "N" & Mid(Cells(lr, 1), 3)
        Else
            Cells(lr, 3) = Cells(lr, 1)
        End If
    Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.