用另一个替换单元格中的值 [英] Replacing a value in a cell with another

查看:53
本文介绍了用另一个替换单元格中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

这篇关于用另一个替换单元格中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆