我想在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
答案 0 :(得分:1)
稍微修改一下代码以适应您描述的需求(如果理解正确)
E1
中搜索值根据您的评论我的示例数据:
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
运行宏后:
以防万一您可以通过公式来执行此操作并避免使用VBA(特别是如果您不熟悉VBA),例如C2
中的内容:
=IF(LEFT(B2,(SEARCH("-",B2)-1))=$E$1,A2&RIGHT(B2,LEN(B2)-SEARCH("-",B2)+1),B2)
然后向下拖动...
答案 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