将 () 替换为带有变量值的范围

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

我在替换范围变量中的值时遇到困难。 我的目标是找到 G 列并将其替换为 A 列中的范围变量。 查找值“0260203700”是固定的。 虽然替换值我需要它们是 A 列范围内的变量。 G 列是一个 URL,需要查找“0260203700”并替换为 A 列范围内找到的变量。

有人可以帮我提供建议或指导吗?

谢谢你。

Sub Bulk_Replace()

Dim listRng As Range

Dim rep As Range

Dim findThis As String

Dim replaceWith As String



With Worksheets("Sheet1")

       Set listRng = .Range(Cells(2, "A"), Cells(Rows.Count, "A").End(xlUp))

 End With

For Each rep In listRng

If Len(rep.Value) = 0 Then GoTo skip   ''' Skip empty cells

    findThis = rep.Value

    replaceWith = rep.Offset(0, 1).Value

    On Error GoTo skip    ''' If not found

    Range("G2:G").Replace What:=findThis, Replacement:=replaceWith

skip: '' Next in line

Next rep

               

End Sub
excel vba replace range
1个回答
0
投票
  • 将 Col A 和 G 加载到数组中
  • 替换内存中的数据
  • 一次性将输出写入 Col G
Option Explicit
Sub Bulk_Replace()
    Dim listRng As Range
    Dim aColG, aColA, i As Long, sVal As String
    Const SKEY = "0260203700"
    With Worksheets("Sheet1")
        Dim lastRow As Long: lastRow = .Cells(.Rows.Count, "G").End(xlUp).Row
        Set listRng = .Range("G1:G" & lastRow)
        aColG = listRng.Value
        aColA = .Range("A1:A" & lastRow).Value
    End With
    For i = LBound(aColG) To UBound(aColG)
        sVal = aColG(i, 1)
        If InStr(sVal, SKEY) > 0 Then
            aColG(i, 1) = Replace(sVal, SKEY, aColA(i, 1))
        End If
    Next
    listRng.Value = aColG
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.