我在查找/替换循环时遇到问题。通过将宏保存到我的个人工作簿,我有一个我希望轻松找到/替换的122个值的列表。我正在尝试简化它,以便每个值都使用逻辑字符串名称定义,然后查找/替换在字符串中递增。这就是我所拥有的:
Sub utf8_cleanup()
' reference: http://www.i18nqa.com/debug/utf8-debug.html
Dim find_prefix As String
Dim replace_prefix As String
Dim find_1 As String
Dim replace_1 As String
Dim find_2 As String
Dim replace_2 As String
Dim find_3 As String
Dim replace_3 As String
Dim replace_count As Integer
find_prefix = "find_"
replace_prefix = "replace_"
find_1 = "Â"
replace_1 = ""
find_2 = "–"
replace_2 = "–"
find_3 = "—"
replace_3 = "—"
' 122 of these pairs
replace_count = 1
Do Until replace_count = 122
find_value = find_prefix & replace_count
replace_value = replace_prefix & replace_count
Debug.Print "Finding " & find_value & "; replacing with " & replace_value
Cells.Replace What:=find_value, Replacement:=replace_value, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, ReplaceFormat:=False
Debug.Print "Done " & replace_count & " replacement(s)"
replace_count = replace_count + 1
Loop
End Sub
最终结果是宏搜索“find_value
”和“replace_value
”的文本,而不是这些字符串的值(例如{{1应转换为“find_2
”,或Â
转换为“replace_2
”)。我确信这是一件非常简单的事情 - 自从我接触VBA以来已经有好几个月了。
提前致谢。
答案 0 :(得分:1)
您正在搜索变量的名称,而不是变量本身。如果你使用数组呢?
Sub utf8_cleanup()
' reference: http://www.i18nqa.com/debug/utf8-debug.html
'Dim find_prefix As String
'Dim replace_prefix As String
'
'Dim find_1 As String
'Dim replace_1 As String
'Dim find_2 As String
'Dim replace_2 As String
'Dim find_3 As String
'Dim replace_3 As String
Dim replace_count As Integer
'find_prefix = "find_"
'replace_prefix = "replace_"
'strings to search:
Dim find_bin(122) As String
Dim replace_bin(122) As String
find_bin(1) = "Â"
replace_bin(1) = ""
find_bin(2) = "–"
replace_bin(2) = "–"
find_bin(3) = "—"
replace_bin(3) = "—"
' 122 of these pairs
replace_count = 0
Do Until replace_count = 122 - 1
find_value = find_prefix & replace_count
replace_value = replace_prefix & replace_count
Debug.Print "Finding " & find_bin(replace_count) & _
"; replacing with " & replace_bin(replace_count)
Cells.Replace What:=find_bin(replace_count), Replacement:=replace_bin(replace_count), _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, ReplaceFormat:=False
Debug.Print "Done " & replace_count & " replacement(s)"
replace_count = replace_count + 1
Loop
End Sub