2

I'm trying to create a vba function to replace multiple characters from cell value. I'm calling this function 'TestFunction' for now. The purpose of the function is to parse illegal characters from the data to be able to use it and the original data needs to remain in their own columns after parse.

I have pasted my code and table as a reference.

+ screen capture from original test

To use the function I would like to use =TestFunction(...) on a helper column on the same row as the data is in. The code works for a single reference e.g. =TestFunction(A1), but when trying to pass concatenated reference e.g. =TestFunction(A1&A2) it returns #VALUE!.

I've tried to fix this for a while with no success. I could make another helper column where the concatenated data is but I would really love to get this function to work without additional column.

Anyone know if this is possible to achieve?

Reference code:

Function TestFunction(CellContents As Range) As String
  Dim CellTextReplaced As String
  Dim char As Variant
  ' Characters to be replaced with "|" as delimiter
  Const SpecialCharacters As String = ".|,|!| |/|\|+|-|@|&"

  ' Replace all special characters
  CellTextReplaced = CellContents.Value
    For Each char In Split(SpecialCharacters, "|")
      CellTextReplaced = Replace(CellTextReplaced, char, "")
    Next
  ' Output

  TestFunction = CellTextReplaced
End Function

Reference table:

  |   A    |    B     |        C           |          D           |
-------------------------------------------------------------------
1 | .test  |   .test  |  =TestFunction(A1) | =TestFunction(A1&B1) |
2 | ,test  |   ,test  |  =TestFunction(A2) | =TestFunction(A2&B2) |
3 | test-  |   test-  |  =TestFunction(A3) | =TestFunction(A3&B3) |
4 | /test\ |   /test\ |  =TestFunction(A4) | =TestFunction(A4&B4) |
2
  • The concatenated one is a string, not a range. Commented Mar 15, 2019 at 10:56
  • 2
    Change the UDF() to accept a String rather than a Range. Commented Mar 15, 2019 at 10:56

1 Answer 1

3

The issue is that your function TestFunction(CellContents As Range) was waiting for a Range but A1&B1 actually is a String because the concatenation with & casts the values of the two ranges A1 and B1 into a string.

I suggest the following improvements:

Option Explicit

Public Function TestFunction(ByVal CellContents As String) As String
    Const SpecialCharacters As String = ".,! /\+-@&"

    Dim iChar As Long
    For iChar = 1 To Len(SpecialCharacters)
        CellContents = Replace$(CellContents, Mid$(SpecialCharacters, iChar, 1), "")
    Next iChar

    TestFunction = CellContents
End Function
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.