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

我正在编码一个VBA函数来合并两个单元格,然后用粗体格式突出显示单元格2的文本

合并进展顺利
对子的呼叫进展顺利
但文本格式不适用

我相信这可能是由单元格填充string之前的子执行引起的 – 但这纯粹是猜测 – 这是我的第一个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循环遍历列,获取两个单元格的string,组合string并将它们添加到目标单元格,同时加粗第二个单元格的文本

感谢@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