Home > OS >  How to Make Part of a (Flexible) String Bold in VBA
How to Make Part of a (Flexible) String Bold in VBA

Time:03-03

I tried to make part of a string bold which look like this

https://i.stack.imgur.com/Ng2P4.png

But the problem is, if I make it A3 = A1&A2 then the code doesn't works.

Here's the code that I tried

Sub bold()

Dim i As Long
Dim cll As Range, rng As Range

Application.ScreenUpdating = False

Set rng = Sheets("Sheet1").Range("A3")

For Each cll In rng
    For i = 1 To Len(cll)
        If Mid(cll, i, 1) = "0" Or Mid(cll, i, 1) = "1" Or Mid(cll, i, 1) = "2" Or Mid(cll, i, 1) = "3" Or Mid(cll, i, 1) = "4" Then
            cll.Characters(Start:=i, Length:=1).font.FontStyle = "bold"
        End If
        If Mid(cll, i, 1) = "5" Or Mid(cll, i, 1) = "6" Or Mid(cll, i, 1) = "7" Or Mid(cll, i, 1) = "8" Or Mid(cll, i, 1) = "9" Then
            cll.Characters(Start:=i, Length:=1).font.FontStyle = "bold"
        End If
        If Mid(cll, i, 1) = "(" Or Mid(cll, i, 1) = ")" Then
            cll.Characters(Start:=i, Length:=1).font.FontStyle = "bold"
        End If
        If Mid(cll, i, 5) = "Sixty" Then
            cll.Characters(Start:=i, Length:=5).font.FontStyle = "bold"
        End If
    Next i
Next cll

Application.ScreenUpdating = True

End Sub

CodePudding user response:

I may have phrased myself wrong

I have zero knowledge of coding before this, but after looking at other's code I've learn something, and this is the kind of solution I was looking for

Sub flexiblebold()
Dim A As Range
Dim B As Range
Dim C As Range
Dim D As Range
Set A = Range("A1")
Set B = Range("B1")
Set C = Range("C1")
Set D = Range("D1")
    With Range("A2")
        .font.Bold = False
        Application.EnableEvents = False
        .Value = [A]   " " & _
        [B]   " " & _
        [C]   " " & _
        [D]
        .Characters(Len([A])   2, Len([B])).font.Bold = True
        .Characters(Len([A])   Len([B])   Len([C])   4, Len([D])).font.Bold = True
        Application.EnableEvents = True
    End With
End Sub

With that solution it will go something like this as text within a cell

A1 B1 C1 D1

Also if somebody can make =bold() function from vba so it could make something like this I would be really grateful!

A3 = A1   BOLD(A2)

CodePudding user response:

That is not possible. You can only make the cell bold if it contains a formula.

  • Related