I am coding a VBA function to merge two cells and then highlight the text of cell 2 with bold formatting
The merging goes well
The call to Sub goes well
But the text format is not applied
I believe it might be caused by the sub executing before the cell is populated with the string - but that's pure guessing - this is my first VBA script
Function boldIt(navn As String, ekstra As String)
Dim ln1 As Integer
Dim ln2 As Integer
Dim st1 As String
ln1 = Len(navn)
ln2 = Len(navn) + Len(ekstra)
If (ln1 = ln2) Then
boldIt = navn
Else
boldIt = navn & " - " & ekstra
boldTxt ln1, ln2
End If
End Function
Public Sub boldTxt(startPos As Integer, charCount As Integer)
With ActiveCell.Characters(Start:=startPos, Length:=charCount).Font
.FontStyle = "Bold"
End With
End Sub
This Sub loops through the columns, takes the strings of the two cells, combines the strings and add them to the target cell, while bolding the text of the second cell
Thanks to @Jeeped for the pointers!
Sub boldIt()
Dim pos_bold As Integer
Dim celltxt As String
For i = 2 To 200000
' first cell will always be populated - if not - exit
If (Range("Plan!E" & i).Value = "") Then Exit For
' if second cell is empty - take only first cell as normal txt
If (Range("Plan!F" & i).Value = "") Then
Range("Kalender!F" & i).Value = Range("Plan!E" & i).Value
Else
' calculate start of bold text
pos_bold = Len(Range("Plan!E" & i).Value) + 1
' create the string
celltxt = Range("Plan!E" & i).Value & " - " & Range("Plan!F" & i).Value
' add string to field and add bold to last part
With Worksheets("Kalender").Range("F" & i)
.Value = celltxt
.Characters(pos_bold).Font.Bold = True
End With
End If
Next i
End Sub