0

我在让查找/替换循环工作时遇到问题。我有一个包含 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" 的文本,而不是那些字符串的(例如find_2应该翻译成 " ­",或replace_2翻译成 " -")。我敢肯定这是非常简单的事情——我接触 VBA 已经几个月了。

提前致谢。

4

1 回答 1

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
于 2013-08-29T12:04:20.267 回答