我有以下代码:
Sub findReplace()
Dim myArray As Variant, rng As Range, str As Variant, cAdd2 As Range
myArray = Array("è", "é", "ë", "ê", "í", "?", "ñ", "ò", "ó", "ô", "ö", "à", "ã", "á", "Á", "ä", "ü", "â", "ø", "š", "??", ">", "<", "+", "*", "^", "ß", "ç", "å", "æ", ".", ";", "#", ":", "'", "-", "@", "Ã", "¨", "É", "Ô", "[", "]", "Ó", "Ñ", "(", ")", "Ö")
Set rng = Workbooks("User").Sheets("Result").Range("B2:B10")
For Each cell In rng
cAdd = cell.Address
Set cAdd2 = Range(cell.Address)
For Each str In myArray
If InStr(cell, str) Then
cAdd2.Offset(, 1).Formula = "=Substitute(" & cAdd & ", " & str & ",""_"")" -->**# This is where I get my error**
Else
cAdd2.Offset(, 1) = "=(" & cAdd & ")"
End If
Next str
Next cell
End Sub
我想要做的是遍历一系列单元格,用单元格旁边的单元格中的下划线替换该单元格中的数组中的任何字符,如果没有特殊字符,则只需复制它。
我认为问题出在cell.Address函数上,但我不确定。
非常感谢任何建议!
谢谢!
答案 0 :(得分:3)
你可以尝试一下吗?还将允许替换多个角色
Sub findReplace()
Dim myArray As Variant, rng As Range, str As Variant
Dim Form As String
myArray = Array("è", "é", "ë", "ê", "í", "?", "ñ", "ò", "ó", "ô", "ö", "à", "ã", "á", "Á", "ä", "ü", "â", "ø", "š", "??", ">", "<", "+", "*", "^", "ß", "ç", "å", "æ", ".", ";", "#", ":", "'", "-", "@", "Ã", "¨", "É", "Ô", "[", "]", "Ó", "Ñ", "(", ")", "Ö")
Set rng = Workbooks("User").Sheets("Result").Range("B2:B10")
For Each cell In rng
Form = "=(" & cell.Address & ")"
For Each str In myArray
If Not str = vbNullString Then
If InStr(cell, str) Then
If Len(Form) > 0 Then
Form = Replace(Form, cell.Address, "Substitute(" & cell.Address & ", """ & str & """,""_"")") ' -->**# This is where I get my error**
Else
Form = "=Substitute(" & cell.Address & ", """ & str & """,""_"")"
End If
End If
End If
Next str
cell.Offset(, 1).Formula = Form
Next cell
End Sub
答案 1 :(得分:1)
该行的错误在我的评论中,但这会更快,因为它只有一个循环并将替换每个特殊字符而不仅仅是最后找到的@Flephal声明:
Sub findReplace()
Dim myArray As Variant, rng As Range, str As Variant
myArray = Array("è", "é", "ë", "ê", "í", "?", "ñ", "ò", "ó", "ô", "ö", "à", "ã", "á", "Á", "ä", "ü", "â", "ø", "š", "??", ">", "<", "+", "*", "^", "ß", "ç", "å", "æ", ".", ";", "#", ":", "'", "-", "@", "Ã", "¨", "É", "Ô", "[", "]", "Ó", "Ñ", "(", ")", "Ö")
Set rng = Workbooks("User").Sheets("Result").Range("B2:B10")
rng.Offset(, 1).Value = rng.Value
For Each str In myArray
rng.Offset(, 1).Replace str, "_"
Next str
End Sub
测试:
Sub findReplace()
Dim myArray As Variant, rng As Range, str As Variant
myArray = Array("E", "S", "!", ")")
Set rng = ActiveSheet.Range("B2:B10")
rng.Offset(, 1).Value = rng.Value
For Each str In myArray
rng.Offset(, 1).Replace str, "_"
Next str
End Sub