如何在cloumn2中找到E1值,然后使用宏替换为column1值?

时间:2019-06-07 10:00:28

标签: excel vba

我想在E1行的column2单元格中找到可用的值,然后替换为column1的值。例如

B2值应从ABC-1替换为A-1。 B3值应从ABC-1替换为B-1

以此类推。

我是宏的新手。

我正试图从互联网上获取代码

Sub FindReplaceAll()

Dim fnd As Variant
Dim rplc As Variant  

fnd = "ABC"
rplc = Cells(i, 8).Value

Dim lastRow As Long
lastRow = Cells(Rows.Count, 4).End(xlUp).row

Dim i As Long

For i = 2 To lastRow
    If Not IsEmpty(Cells(i, 4)) Then
          Cells.Replace what:=fnd, Replacement:=rplc
    End If
Next

End Sub

3 个答案:

答案 0 :(得分:1)

稍微修改一下代码以适应您描述的需求(如果理解正确)

  • 您始终在绝对单元格E1中搜索值
  • 您将B列中的searchvalue替换为A列中的完整值

根据您的评论我的示例数据:

enter image description here

Sub FindReplaceAll()

Dim fnd As String, rplc As String, i As Long

With ActiveWorkbook.Sheets("Sheet1") 'Your sheetname goes here
    fnd = .Range("E1").Value
    For i = 2 To .Cells(Rows.Count, 1).End(xlUp).Row
        .Cells(i, 2).Replace what:=fnd, Replacement:=.Cells(i, 1).Value
    Next i
End With

End Sub

运行宏后:

enter image description here

以防万一您可以通过公式来执行此操作并避免使用VBA(特别是如果您不熟悉VBA),例如C2中的内容:

=IF(LEFT(B2,(SEARCH("-",B2)-1))=$E$1,A2&RIGHT(B2,LEN(B2)-SEARCH("-",B2)+1),B2)

然后向下拖动...

enter image description here

答案 1 :(得分:0)

有关更多详细信息,请参见代码中的注释,但请告诉我这是否满足您的要求:

Sub FindReplaceAll()

Dim ws As Worksheet: Set ws = ActiveWorkbook.Sheets("sheet name") '<-- set your sheet name
Dim lRow As Long: lRow = ws.Cells(Rows.Count, "A").End(xlUp).Row 'get last row in column A
Dim arrData As Variant: arrData = ws.Range("A1:E" & lRow) 'declare and allocate data to an array

Dim R As Long, C As Long

For R = LBound(arrData) To UBound(arrData)
    If arrData(R, 5) = arrData(R, 2) Then 'if E matches the value in B
    'If arrData(1, 5) = arrData(R, 2) Then 'Alternative if E1 is a fixed value, and not for every row
        ws.Cells(R, 2) = arrData(R, 1) 'allocate the A value to B
    End If
Next R

End Sub

答案 2 :(得分:0)

尝试:

Option Explicit

Sub FindReplaceAll()

    Dim SearchString As String
    Dim LastRow As Long, i As Long

    With ThisWorkbook.Worksheets("Sheet1")
        'Find the last row of column A
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        'Set the SearchString equal to the value of cell E1
        SearchString = .Range("E1").Value

        'Loop from second row to lastrow
        For i = 2 To LastRow
            'If the value of cell B & i equal to SearchString
            If (.Range("B" & i).Value <> "") And (.Range("B" & i).Value = SearchString) Then
                'Cell B & i equal to A & i
                .Range("B" & i).Value = .Range("A" & i).Value
            End If

        Next i

    End With

End Sub