【问题标题】:Excel VBA Replace using String to Find and Array Value to ReplaceExcel VBA替换使用字符串查找和数组值替换
【发布时间】:2017-02-16 14:11:43
【问题描述】:

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

代码旨在循环遍历一个表,并且对于列 [Variable] 下的每一行,将该变量的任何实例替换为“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))

我已经搜索过,但最终胜出。

任何帮助都会很棒。

标记

【问题讨论】:

  • 您最好展示一些数据示例。

标签: excel vba replace


【解决方案1】:

每次通过循环,您都对原始blankLetter 参数进行一次替换,并将结果放入letterReplace:只有最后一个替换操作会将其作为返回值从函数中取出。

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

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

【讨论】:

  • 感谢蒂姆·威廉姆斯的帮助,工作完美且有意义。干杯。
猜你喜欢
  • 1970-01-01
  • 2013-07-15
  • 2021-12-11
  • 2019-02-07
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 2019-10-23
相关资源
最近更新 更多