在VBA中替换循环

时间:2012-03-07 18:45:02

标签: vba

我有一些带有一些特殊字符的csv文件,例如'è'而不是'é'(csv文件是法语)。 所以基本上我引用了所有特殊字符,我正在尝试用VBA编写代码来实现它。不幸的是,它无法正常工作。 我的代码是:

Sub ReplaceTest()

' I referenced 35 issues

    Dim replaceWhat(35) As Variant
    Dim replaceBy(35)  As Variant
 ' This is where I reference the special caracters and link them to the good ones
    Application.Sheets("SpecialCaracters").Select
    replaceWhat(35) = Application.Range("A1:A35").Value 
    replaceBy(35) = Application.Range("B1:B35").Value

    Dim i As Integer
    For i = 0 To 34
        Application.Sheets("Sheet1").Select
        ActiveSheet.Columns("A:AH").Select

        Selection.Replace What:=remplacerWhat(i), Replacement:=remplacerBy(i),  LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Next i
End Sub

有什么想法吗?感谢

1 个答案:

答案 0 :(得分:4)

假设你有这样的事情:

SpecialCharacters Sheet
\ | A | B
1 | à | a
2 | é | e
3 | ó | o

您可以使用以下方法迭代所有特殊字符行,并替换其他工作表或范围中的实例。

Option Explicit

Sub ReplaceSpecialCharacters(ReplaceRange As Range)
    Dim SpecialCharSheet As Worksheet
    Dim replaceWhat As String
    Dim replaceBy  As String
    Dim RowIndex As Long

    Set SpecialCharSheet = Sheets("SpecialCharacters")
    For RowIndex = 1 To SpecialCharSheet.UsedRange.Rows.Count
        replaceWhat = SpecialCharSheet.Cells(RowIndex, 1).Value
        replaceBy = SpecialCharSheet.Cells(RowIndex, 2).Value

        ReplaceRange.Replace What:=replaceWhat, Replacement:=replaceBy, _
            LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
            SearchFormat:=False, ReplaceFormat:=False
    Next RowIndex
End Sub

Sub ReplaceSheet1()
    ' If using hard coded range
    ReplaceSpecialCharacters Sheet1.Columns("A:AH")

    ' If using Selection
    ReplaceSpecialCharacters Selection
End Sub