Please forgive if the question has been asked before but I'm new to Excel VBA and stackoverflow.
I'm trying to write a custom function to merge two cells together maintaining the original formatting in the two cells. I.e. Cell1 contains "Hello" in bold and Cell2 " World" in normal then I want Cell3 (containing the formula) to return "Hello World". Obviously I need to use the .Characters call to loop through the original strings and apply that to the final string. So I can't just return a string ('cause I lose the formatting) I have to return a .Range object. But I descended into a world of pain before I even got to the .Characters bit.
My first attempt looked like this:
Public Function Merge_Formats(inCellOne As Range, inCellTwo As Range) As Range
On Error GoTo ErrorTrap
Merge_Formats.Text = inCellOne.Text & inCellTwo.Text
Exit Function
ErrorTrap:
MsgBox Err.Description
End Function
That returned: Object variable or With block variable not set
Then I tried accessing the cell that contains my function:
Public Function Merge_Formats(inCellOne As Range, inCellTwo As Range) As Range
Dim tempCell As Range
On Error GoTo ErrorTrap
Set tempCell = Application.Caller
tempCell.Text = inCellOne.Text & inCellTwo.Text
Exit Function
ErrorTrap:
MsgBox Err.Description
End Function
Which throws this: Object Required
I also tried (as a nasty workaround) to pass a third cell to be used as a staging post:
Public Function Merge_Formats(inCellOne As Range, inCellTwo As Range, tempCell As Range) As Range
On Error GoTo ErrorTrap
tempCell.Text = inCellOne.Text & inCellTwo.Text
Exit Function
ErrorTrap:
MsgBox Err.Description
End Function
This also returns the Object Required error message.
I know I can reference another cell:
Function SimpleTest() As Range
Dim tempCell As Range
Set tempCell = Range("A1")
Set SimpleTest = tempCell
End Function
Clearly I'm out of my depth here. Is it possible to write a custom function returning a .Range object that is not merely referencing another but allowing the contents to be manipulated. If so, how is it done?


Worksheet_Change-Trigger so that your code is called every time something is changed in your sheet.