Excel VBA替换使用String查找和要替换的数组值

时间:2017-02-16 02:45:22

标签: excel vba replace

只需使用以下代码块寻求帮助即可。我在这里要做的是将字母中包含的静态变量替换为相应的值。

代码用于循环遍历表格,并且对于列下的每一行[变量]将该变量的任何实例替换为' blankLetter'中的变量。也许这不是实现这一目标的最佳方式......

Public Function letterReplace(blankLetter As String, letterArray As Dictionary) As String
'Lookup the variable table and for each variable replace the instance of that in the array
Application.ScreenUpdating = False
Dim row As Range
Dim temp As String
For Each row In [varTable[Variable]].Rows
    'temp = "<PURVNAME>"
    temp = row.Value
    letterReplace = Replace(blankLetter, temp, letterArray(temp))
Next
Application.ScreenUpdating = True
End Function

以下工作正常:

letterReplace = Replace(blankLetter, "<PURVNAME>", letterArray("<PURVNAME>"))

然而,这一行并没有取代任何东西:

letterReplace = Replace(blankLetter, temp, letterArray(temp))

我有一个搜索,但即将成为王牌。

任何帮助都会很棒。

标记

1 个答案:

答案 0 :(得分:0)

每次循环时,你都会对原始blankLetter参数进行一次替换,并将结果放在letterReplace中:只有最后一次替换操作才能使其退出函数返回值。

您需要继续对同一个变量执行Replace操作。

Public Function letterReplace(blankLetter As String, letterArray As Dictionary) As String
'Lookup the variable table and for each variable replace the 
'   instance of that in the array

    Dim row As Range, retVal As String
    Dim temp As String

    retVal = blankLetter
    For Each row In [varTable[Variable]].Rows
        temp = row.Value
        retVal  = Replace(retVal, temp, letterArray(temp))
    Next

    letterReplace = retVal
End Function