我写的以下函数返回""每当我尝试在包含公式的范围上使用它时。奇怪的是,当我测试在即时窗口中为rngPhrase
和rngTextBlocks
返回的值时,它会返回正确的结果。
我可以通过为第一个范围添加.Text
(而不是使用默认的.value
或甚至.value2
)来获得第一个范围的正确结果,但这并非如此。适用于阵列。
这里发生了什么,我该如何解决?
Public Function SelectionReplacer(rngPhrase As Range, rngTextBlocks As Range) As String
Dim arr
Dim strTextBlocks As String
Dim strPhrase As String
Dim i As Integer, j As Integer
'set initial phrase (must be a single cell)
strPhrase = rngPhrase.Text
'Set text block array
arr = rngTextBlocks
For i = LBound(arr, 1) To UBound(arr, 1)
If InStr(1, strPhrase, arr(i, 1)) > 0 Then
SelectionReplacer = Replace(strPhrase, arr(i, 1), arr(i, 2))
End If
Next i
End Function
UPDATE 输入的例子
rngPhrase = Range("D34")
,此单元格中的值由vlookup函数计算,该函数返回字符串"[Anrede] [FullName] verfügt über ein äußerst [Art1] und [Art2] Fachwissen, das [Gender1] stets effektiv und erfolgreich [Können1] konnte. [Können2]"
rngTextBlocks
具有类似的功能,所有这些功能都有各自的vlookup函数返回的类似文本元素。
答案 0 :(得分:2)
您只替换了其中一个文本,因此只替换了该范围的最后一行。
您需要使用strPhrase
更改Replace
,然后将其分配给SelectionReplacer
。实际上,无需在Replace
之前进行测试只有找到文本才会出现! ;)
如果rngPhrase
超过一个单元格,我还添加了一个检查以正确退出该函数:
Public Function SelectionReplacer(rngPhrase As Range, rngTextBlocks As Range) As String
'(must be a single cell)
If rngPhrase.Cells.Count > 1 Then
SelectionReplacer = vbNullString
Exit Function
End If
Dim arr
Dim strTextBlocks As String
Dim strPhrase As String
Dim i As Integer, j As Integer
'set initial phrase
strPhrase = rngPhrase.Value
'Set text block array
arr = rngTextBlocks.Value
For i = LBound(arr, 1) To UBound(arr, 1)
strPhrase = Replace(strPhrase, arr(i, 1), arr(i, 2))
Next i
SelectionReplacer = strPhrase
End Function
答案 1 :(得分:1)
我认为轻微的改变会使它按照你想要的方式行事:
Public Function SelectionReplacer(rngPhrase As Range, rngTextBlocks As Range) As String
Dim arr
Dim strTextBlocks As String
Dim strPhrase As String
Dim i As Integer, j As Integer
'set initial phrase (must be a single cell)
strPhrase = rngPhrase.Text
'Set text block array
arr = rngTextBlocks
For i = LBound(arr, 1) To UBound(arr, 1)
If InStr(1, strPhrase, arr(i, 1)) > 0 Then
strPhrase = Replace(strPhrase, arr(i, 1), arr(i, 2)) ' alter strPhrase for each iteration
End If
Next i
SelectionReplacer = strPhrase ' load strPhrase back to SelectionReplacer
End Function