Range中的值不会传递给UDF中的数组

我写下面的函数返回“”,只要我试图在包含公式的范围上使用它。 奇怪的是,当我testing立即窗口中返回rngPhraserngTextBlocks值时,返回正确的结果。

我可以通过在第一个范围内附加.Text (而不是使用默认的.value或甚至.value2 )来得到第一个范围的正确结果,但是这对Array不起作用。

这里发生了什么,我该如何解决呢?

  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 

更新input示例

rngPhrase = Range("D34") ,这个单元格中的值是通过返回string"[Anrede] [FullName] verfügt über ein äußerst [Art1] und [Art2] Fachwissen, das [Gender1] stets effektiv und erfolgreich [Können1] konnte. [Können2]"

rngTextBlocks具有类似的function,所有这些function都有各自的查找function返回的相似的文本元素。

您只replace其中一个文本,所以只能replace范围的最后一行。

您需要更换strPhraseReplace ,然后将其分配给SelectionReplacer
顺便说一句,没有必要在Replace之前testing,因为它只会发生,如果文本被发现! ;)

如果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 

我认为微小的变化会使它按照你想要的方式行事:

 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