Excel VBA:将字符串替换为另一个单元格中的文本

时间:2016-08-13 02:45:32

标签: excel-vba vba excel

在这里,我有一项艰巨的任务。任何帮助将不胜感激。感谢。

我有这样的excel表:

![enter image description here

我想用B列中的文本替换B列和后面的~。所以结果将是这样的:

enter image description here

在VBA代码中请忽略颜色,我只是用它来更好地表示。

我可以理解循环功能是必需的。当检测到空单元时,请停止或跳出循环。

谢谢!

2 个答案:

答案 0 :(得分:1)

它有点快速和肮脏,但它将完成工作

Sub ReplaceChar()

Dim toReplace As String
Dim ReplaceWith As String
Dim Col As Long
Dim lRow As Long


toReplace = "~"
ReplaceWith = "bbb"

' replacing all ~ from the first row
For lRow = 1 To Cells(Rows.Count, "B").End(xlUp).Row
    ' starting from Column B
    For Col = 2 To Cells(1, Columns.Count).End(xlToLeft).Column
        Cells(lRow, Col) = Replace(Cells(lRow, Col), toReplace, ReplaceWith)
    Next Col
Next lRow

End Sub

答案 1 :(得分:1)

根据图片的布局,您可以尝试以下代码:

Sub ReplaceTextWithString()
Dim Text As String, Str As String, NewText As String
Dim LastRow As Long, iRow As Long, iCol As Long

LastRow = Cells(Rows.Count, 1).End(xlUp).Row    'Find the last row in column 1 (A)

For iRow = 2 To LastRow                         'Loop through column 1 from row 2 to LastRow
    Str = Cells(iRow, 1)                        'Set string value to replace "~"
    iCol = 2                                    'Initial value for a starting column
    Do                                          'Loop through columns in row iRow
        Text = Cells(iRow, iCol)
        NewText = Application.WorksheetFunction.Substitute(Text, "~", Str)
        Cells(iRow, iCol) = NewText
        iCol = iCol + 1
    Loop Until Cells(iRow, iCol) = vbNullString 'Loop until there's no cell to be replaced
Next
MsgBox "The task is 100% completed."            'Optional
End Sub

对于将来的参考,您可能会看到:Excel VBA: How to remove substrings from a cell?