Formatting a newly created comment in VBA

Karen 0 Reputation points
2024-02-21T16:35:39.8533333+00:00

I have written a function in VBA. I print the returned value to the cell and add a comment that contains any warnings during the calculation. I am adding comments by using "Application.Caller" to reference the cell. I am finding that the code typically used to format comments in VBA seems to be hit or miss when applied to my "new" comment. For example, the following lines of code work fine:

  • Application.Caller.AddComment msg
  • Application.Caller.Comment.Shape.Width = 300
  • Application.Caller.Comment.Shape.Height = 50

However, the following lines of code do NOT work:

  • Application.Caller.Comment.Shape.TextFrame.Characters.Font.Bold = False
  • Application.Caller.Comment.Shape.TextFrame.Characters(1, 10).Font.Bold = True
  • Application.Caller.Comment.Shape.TextFrame.AutoSize = True

I have found that if I place all 6 lines in a sub and call that after my function has run replacing Application.Caller with Range("A1"), they all work fine, which tells me the syntax is good. I also tried to call that subroutine from my function and passed Application.Caller as the range, then Application.Caller.Address as a string, neither of which worked. I need a solution that I can call from my function for only that cell, so none of the proposed solutions I have found will work for me (i.e. run another sub after the fact to loop over all comments in a worksheet to reformat them). It almost seems that the TextFrame object isn't valid in the function so is there another way to format the text of a comment I can try instead?

Also, I realize that the Width/Height commands are silly if the AutoSize were working, I added those after AutoSize failed to see if they work, which surprisingly they do, so I can live with that workaround. I also tested if you can change the shape of the comment box, which also works but I don't really want to do that. Mostly, I really want to unbold the font, which is what it's currently doing, so it's more comfortable to read for the user.

Thanks!

Microsoft 365 and Office Development Other
Microsoft 365 and Office Install, redeem, activate For business Windows
Microsoft 365 and Office Excel For business Windows
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.