2015-11-16 73 views
1

這是討論Looping through values in cells to replace in the text通過用戶定義的範圍

下面的代碼採取在單元中的值的延續D2,並在所有情況下OriginalText其中單詞「標記名填充其值做,直到爲IsEmpty到環「 用來。然後它遍歷loopText範圍並生成correctedText範圍。 我正在尋找使用Do UntilEmpty命令循環,以便loopText範圍取決於用戶範圍輸入,說如果用戶填充單元格D2:D54那麼所有的然後執行。

下面是我的代碼,但我不斷收到運行時錯誤「91」

對象變量或帶塊變量未設置

請幫助。 謝謝。

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

Do Until IsEmpty(loopText.Value) 

Set correctedText = Range("B10") 
Set OriginalText = Range("H3:H20") 
Set loopText = Range("D2") 
i = 0 
Columns(2).Clear 
For Each cel2 In loopText 

    For Each cel In OriginalText 
     correctedText.Offset(i).Value = Replace(cel.Value, "tagname", cel2.Value) 
     i = i + 1 
    Next cel 

Next cel2 

Loop 

End Sub 

回答

0

試試這個:

你只需要兩個循環,第一個循環改爲你在找什麼。

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

Set correctedText = Range("B10") 
Set OriginalText = Range("H3:H20") 
Set loopText = Range("D2") 
i = 0 
j = 0 
Columns(2).Clear 

Do Until IsEmpty(loopText.Offset(j).Value) 

    For Each cel In OriginalText 
     correctedText.Offset(i).Value = Replace(cel.Value, "tagname", loopText.Offset(j).Value) 
     i = i + 1 
    Next cel 
    j = j + 1 
Loop 

End Sub 
+0

謝謝@ scott-craner! –