2016-08-30 33 views
0

在工作表Sheet1中,我需要通過列A並查找Sheet2列的任何值。 A並替換由Sheet2 col找到的字符串。 B值。用於替換2列查找中的單元格內容的Excel宏

例如,如果我在Sheet1.A和Sheet2.A234中的某處「每天去http://google.com」,我需要用Sheet2.B234值(「stackoverflow」)替換原始字符串以獲得「每天轉到http://stackoverflow.com「到原始單元格或新列中。 如果沒有找到,沒有變化。

我不太瞭解vba,我只是稍微修改了一些在這裏和那裏找到的代碼。我知道如何做一個公式來做到這一點,但我可以在這種情況下得到任何循環/範圍。

任何幫助表示讚賞:)

弗雷德

YowE3K的偉大工程,那麼優雅,但工作壓力太大:

Sub remplace() 

Dim myInput As String, myTest As String, myReplacement As String 

For i = 1 To 8 'for 10 rows of data in Sheet2 
    For j = 1 To 4 'for 5 rows of data in Sheet1 

     myInput = Sheets("Sheet3").Cells(j, 1).Value 
     myTest = Sheets("Sheet4").Cells(i, 1).Value 
     myReplacement = Sheets("Sheet4").Cells(i, 2).Value 

     resultText = Replace(myInput, myTest, myReplacement) 

     Sheets("Sheet3").Cells(j, 1).Value = resultText 

    Next j 
Next i 

End Sub 
+0

你可能會考慮展示您的公式,可能會幫助別人瞭解你在做什麼,使他們更容易來幫助你:) –

回答

0

下面的代碼將做的工作

Sub foo() 

For i = 1 To 10 'for 10 rows of data in Sheet2 
    For j = 1 To 5 'for 5 rows of data in Sheet1 
     If Sheets("Sheet2").Cells(i, 1).Value = Sheets("Sheet1").Cells(j, 1).Value Then 
      Sheets("Sheet1").Cells(j, 1).Value = Sheets("Sheet2").Cells(i, 2).Value 
     End If 
    Next j 
Next i 

End Sub 
+0

喜托馬斯,謝謝您幫助,我剛剛調整了您的代碼來執行替換,因爲我的值不是「等於」並需要部分替換。上面的結果;) –

+0

很高興知道你找到了解決方案 –

1

的下面的代碼應該做你想做的事情,但如果你有大的話可能不會非常有效e Sheet1或Sheet2中的行數。 (「大」可能意味着> 1000)

Sub ReplaceValues 
    Dim ws1 As Worksheet 
    Dim ws2 As Worksheet 
    Dim rows1 As Long 
    Dim rows2 As Long 

    Dim row1 As Long 
    Dim row2 As Long 

    Set ws1 = Worksheets("Sheet1") 
    Set ws2 = Worksheets("Sheet2") 

    rows1 = ws1.Range("A" & ws1.Rows.Count).End(xlUp).Row 
    rows2 = ws2.Range("A" & ws2.Rows.Count).End(xlUp).Row 

    For row1 = 1 To rows1 
     For row2 = 1 To rows2 
      ws1.Cells(row1, 1).Value = Replace(ws1.Cells(row1, 1).Value, _ 
               ws2.Cells(row2, 1).Value, _ 
               ws2.Cells(row2, 2).Value) 
     Next 
    Next 
End Sub 
+0

謝謝,很棒的解決方案! –

相關問題