使用VBAmacros在一个单元格中查找并replace部分string中的单元格的值

我在excel的一行中有多个单元格,都包含HTML。 每个单元格都有不同的lang,但是在整个例子中都有相同的URL:(… loc = en-uk)我需要在每个单元格中find并replace它,但每个单元格的值不同,例如:find“en-uk “在单元格A中,replace为”it-it“,移动到下一个单元格,find”en-uk“,replace为”es-es“等,直到到达空单元格为止。

曾尝试以下,但它只需要find并从相同的2个单元格中取代值:

Dim Findtext As String Dim Replacetext As String Findtext = Range("B2").Value Replacetext = Range("C2").Value Cells.Replace What:=Findtext, Replacement:=Replacetext, LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False 

您将需要使用单元格而不是范围,并使用variables“lCol”遍历列。 范围(列字母,行号)有它的限制,因为你正在使用一个字母。 很难把1加到C .. C + 1 = D? 所以使用Cells(row#,col#)。 这样,您就可以通过使用数字而不是字母的列或行来递增式地工作。 在这种情况下,variables是列,所以我们将使用lCol并从1循环到最后一个列号。 以原始postreplace原始源string中的文本作为起点。

注意:我不确定你的原始string在哪里。 另外,如果你知道你要从原始string中取代什么,并且发现自己在整个表单中看到Row2是完全相同的东西,那么你可以在下面的replaceString语句中设置它。

尝试一下 – 一旦你拿出所有的评论,这只是几行。

 Sub TextReplace() Dim sheetName As String Dim findText As String Dim replaceText As String Dim lastCol As Long Dim lCol As Long 'Set the sheetName here, so you don't have to change it multiple times later sheetName = "Sheet1" 'Check the Last Column with a value in it in Row 3. Assuming Row 3 has the Replacement text. lastCol = Sheets(sheetName).Cells(3, Columns.Count).End(xlToLeft).Column 'Assuming you have an original string in a cell. Range("A1"), in this case. origString = Sheets(sheetName).Cells(1, 1).Value 'Loop through each Column - lCol is going to increase by 1 each time. 'Starting on Column B,since Column A contains your original String. For lCol = 2 To lastCol 'Using Cells(row#, col#), instead of Range(ColLetter, row#) gives you the ability to loop with lCol. findText = Sheets(sheetName).Cells(2, lCol).Value replaceText = Sheets(sheetName).Cells(3, lCol).Value 'Put the value from Range("A1") with the text replaced from Row 2 with Row 3's value. Sheets(sheetName).Cells(1, lCol) = Replace(origString, findText, replaceText) Next lCol End Sub 

编辑:更新列开始B,而不是A.

试试这个(例如第16行和第20行):

 Sub ReplaceTextinRow() Dim lastCol, iter lastCol = ActiveSheet.UsedRange.Columns.Count 'this approach is not always applicable For iter = 1 To lastCol 'Cells(16, iter).Offset(4, 0).Value = Replace(Cells(16, iter).Value, "en-us", "en-uk") Cells(20, iter).value = Replace(Cells(20, iter).value, Cells(20, iter).Offset(-4, 0).Value) Next End Sub