繁体   English   中英

用另一个替换单元格中的值

[英]Replacing a value in a cell with another

我在Excel电子表格中编写一个宏,用一个单元格的内容替换一个单元格中的值,并在每次看到此单词时循环遍历替换相同值的原始文本。 例如,我在一系列单元格中有一个文本,其中每行都有一个单词“ tagname”,我想用同一电子表格的单元格A1的值替换“ tagname”,例如说“ Maggie”而不是tagname 。 到目前为止,这是我的代码:

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

我收到运行时错误424,需要对象。

只是将所有内容放在一起,这就是我要做的。

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

或者,如果您真的想要循环:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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