Это может помочь
Sub FindAndChangeText()
Dim i As Range: Set i = Range("A1:Z100") 'Here you store a range with the text you need to change
Dim Str01 As String: Str01 = "1st" 'This is the text you want to find inside the (i) range
Dim Str02 As String: Str02 = "2nd" 'This is the new string you want instead
Dim j As Range
For Each j In i 'With this you goes through every cell in the range, no matter is merge or not.
If InStr(1, j.Value, Str01, 0) <> 0 Then ' if inside the cell exists the string you are looking for, the return something different to zero
j.Replace Str01, Str02, xlPart 'xlPart = 2 review documentation for more info about range.replace and InStr(). Here you change the value inside your string
End If
Next j
End Sub
Функция InStr
Возвращает вариант (Long), указывающий позицию первоговхождение одной строки в другую.
Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP" ' String to search in.
SearchChar = "P" ' Search for "P".
' A textual comparison starting at position 4. Returns 6.
MyPos = Instr(4, SearchString, SearchChar, 1)
' A binary comparison starting at position 1. Returns 9.
MyPos = Instr(1, SearchString, SearchChar, 0)
' Comparison is binary by default (last argument is omitted).
MyPos = Instr(SearchString, SearchChar) ' Returns 9.
MyPos = Instr(1, SearchString, "W") ' Returns 0.
Range.Replace метод
Возвращает логические обозначающие символы вячейки в указанном диапазоне. Использование этого метода не меняет ни выделение, ни активную ячейку.
Worksheets("Sheet1").Columns("A").Replace _
What:="SIN", Replacement:="COS", _
SearchOrder:=xlByColumns, MatchCase:=True
Вы можете сделать что-то, чтобы обойти ячейки с пустыми значениями.
Sub FindAndChangeText()
Dim i As Range: Set i = Range("A1:D10") 'Here you store a range with the text you need to change
Dim Str01 As String: Str01 = "1st" 'This is the text you want to find inside the (i) range
Dim Str02 As String: Str02 = "2nd" 'This is the new string you want instead
Dim j As Range
For Each j In i
If Not j.Value = "" Then
If InStr(1, j.Value, Str01, 0) <> 0 Then
j.Replace Str01, Str02, xlPart 'xlPart = 2
End If
End If
Next j
End Sub
Ошибки
В вашем коде:
Dim rng As Range
rng = Range("A1:K10").Text 'To store a Range type var, you need to use "Set"
'Set rng = youRange
'the whole object. Not just the .text or .value or .address
'those are components inside the object Range, with their own
'different type of value (string, int, double, etc)
rng.Text = Replace(rng, "1st", "2nd") 'If you store the var in the right way
'set rng = yourRange
'You can not take the text inside the whole range.
'Because you have several cells inside your range
'with text in every cell
'that is why you need to go for every cell in yourRange
'Also REPLACE is a method for a cell inside a Range.