简体   繁体   中英

Replacing a value in a cell with another

I am writing a macro in Excel spreadsheets to replace a value in one cell by the content of another cell and loop through the original text replacing the same value, whenever it sees this word. For example, I have a text in a range of cells, where every line has a word "tagname" I want to replace "tagname" with the value of cell A1 of the same spreadsheet, for example to say "Maggie" instead of tagname. This is my code thus far:

Private Sub CommandButton21_Click()
Dim OriginalText As Range
Dim CorrectedText As Range
'definition of ranges

Set OriginalText = Range("H4:H10")

'setting of ranges

For Each OriginalText In CorrectedText

CorrectedText.Value = Replace(OriginalText.Value, "tagname", Range("D2").Value)

Next OriginalText
'a loop through the original text to replace the word "tagname" with the value of cell D4

Columns(2).Clear 'clear column 2 for the Corrected Text
Range("A24:A30").Offset(, 1).Value = CorrectedText
'copy corrected text in these cells
End Sub

I get runtime error 424, object required.

Just to put all of it together, this is how I would do it.

Sub CommandButton21_Click()
Dim correctedText As Range
Dim OriginalText As Range
Dim i As Long
Dim cel As Range

Set correctedText = Range("B24")
Set OriginalText = Range("H4:H10")

OriginalText.Replace "tagname", Range("d4")
correctedText.Resize(OriginalText.Rows.Count).Value = OriginalText.Value
OriginalText.Replace Range("d4"), "tagname"

End Sub

Or if you really want the loop:

Sub CommandButton21_Click()
Dim correctedText As Range
Dim OriginalText As Range
Dim i As Long
Dim cel As Range

Set correctedText = Range("B24")
Set OriginalText = Range("H4:H10")
i = 0
For Each cel In OriginalText
    correctedText.Offset(i).Value = Replace(cel.Value, "tagname", Range("d4"))
    i = i + 1
Next cel

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM