VBA 合并单元格和第二个单元格的**粗体**文本

VBA merge cells and **Bold** text of second cell

我正在编写一个 VBA 函数来合并两个单元格,然后使用 粗体 格式

突出显示单元格 2 的文本

合并顺利
对 Sub 的调用很顺利
但是没有应用文本格式

我相信这可能是由于在用字符串填充单元格之前执行子程序引起的 - 但那纯属猜测 - 这是我的第一个 VBA 脚本

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

我想我会 运行 两个潜艇;该函数未返回任何内容。

Option Explicit

Sub boldIt()
    Dim secondOne As String
    With Selection
        secondOne = .Cells(2).Value2
        Application.DisplayAlerts = False
        .Merge
        Application.DisplayAlerts = True
        .Cells(1) = .Cells(1).Value2 & secondOne
        boldTxt .Cells(1), Len(.Cells(1).Value2) - Len(secondOne) + 1, Len(secondOne)
    End With
End Sub

Public Sub boldTxt(rng As Range, startPos As Integer, charCount As Integer)
    With rng.Characters(Start:=startPos, Length:=charCount).Font
        .FontStyle = "Bold"
    End With
End Sub

这个 Sub 遍历列,获取两个单元格的字符串,组合字符串并将它们添加到目标单元格,同时将第二个单元格的文本加粗

感谢@Jeeped 指点!

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