2015-11-13 162 views
0

我正在Excel電子表格中編寫一個宏,以便用另一個單元格的內容替換一個單元格中的值,並在每次看到該單詞時循環顯示替換相同值的原始文本。 例如,我在單元格範圍內有一個文本,其中每行都有一個單詞「tagname」,我想用同一電子表格的單元格A1的值替換「tagname」,例如說「Maggie」,而不是標籤名。 這是我的代碼至今:需要用另一個單元格替換單元格中的值

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,對象。

+0

最後一行應該是'範圍。( 「A24:A30」)偏移(1).value的= CorrectedText.Value' –

+0

那被說你不需要循環,看來你正在替換。而不是整個循環只是放置這個:'correctedText.Replace什麼:=「標記名」,替換:=範圍(「D2」)' –

回答

0

只是把它放在一起,這就是我將如何做到這一點。

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 
+0

謝謝你,斯科特,像魔術一樣工作。 –

+0

我現在正在循環遍歷範圍D4到D10,一遍又一遍地執行相同的循環。我嘗試了2個循環,一個在另一個內,但我得到的是相同的文本三次。你可以善意地循環我的代碼,看看我錯了哪裏? –

+0

子CommandButton21_Click() 昏暗correctedText作爲範圍 昏暗OriginalText作爲範圍 昏暗我只要 昏暗J所示龍 昏暗CEL1作爲範圍 昏暗CEL2作爲範圍 集correctedText =範圍( 「B24」) 集OriginalText =範圍( 「H3:H20」) 集loopText =範圍( 「D2:D4」) I = 0 J = 0 對於每個CEL2在loopText 對於每個CEL1在OriginalText correctedText.Offset(ⅰ)。價值=替換(cel1.Value,「tagname」,Range(「D2」)) i = i + 1 Next cel1 j = j + 1 Next cel2 End Sub –

相關問題