2009-09-10 33 views
2

在下面的代码中,我采用了一些输入参数,无论是文本还是单元格,并将它们组合成一个使用我需要的格式的字符串。我需要使Task_Name变为粗体,以及像“Lead:”这样的文本。我知道你不能以粗体显示变量,但我该怎么做?我存储该值的单元格最终将用于Word邮件合并。如何在VBA中设置文本/字符串的格式?

我需要格式化字符串的一部分。在下面的代码中,我需要将Task_Name,“Lead:”等全部加粗。

Function GENERATE_STAFFING_SECTION(Task_Name, Lead_By, Members, Instructions) 
    Dim tmpSection As String 

    If Len(Task_Name > 0) And Len(Lead_By) > 0 And Len(Members) > 0 And Len(Instructions) > 0 Then 
     tmpSection = vbLf _ 
        & Task_Name _ 
        & vbLf & "Lead : " & Lead_By _ 
        & vbLf & "Ambassadors : " & Members _ 
        & vbLf & "Instructions : " & Instructions _ 
        & vbLf 
    Else 
     tmpSection = "" 
    End If 

    GENERATE_STAFFING_SECTION = tmpSection 
End Function 

而且,我知道这不是最干净的代码,因此,如果有如果有改进的其他建议,他们是最欢迎的。

谢谢!

回答

5

您不能直接向字符串添加任何内容以使单元格具有粗体字符。

一旦将字符串写入单元格,您需要返回并重新处理单元格。 例如:

With ActiveCell.Characters(Start:=11, Length:=6).Font 
    .Name = "Arial" 
    .FontStyle = "Bold" 
    .Size = 10 
    .Strikethrough = False 
    .Superscript = False 
    .Subscript = False 
    .OutlineFont = False 
    .Shadow = False 
    .Underline = xlUnderlineStyleNone 
    .ColorIndex = xlAutomatic 
End With 

这个片段将仅在小区的一部分设置为粗体。

编辑:

该代码可以用来实现上述,给你想要的东西。 它可以写更好,但应该给你的你有什么写什么的想法:

Public Sub FormatOuput() 

    Dim i As Integer 

    'Format Task_name 
    i = InStr(1, ActiveCell.Text, vbLf) 
    MakeBold 1, i 

    'Format 'Lead' 
    MakeBold i + 1, 4 

    'Format 'Ambassadors' 
    i = InStr(i + 1, ActiveCell.Text, vbLf) 
    MakeBold i+1, 11 

    'Format 'Instructions' 
    i = InStr(i + 1, ActiveCell.Text, vbLf) 
    MakeBold i+1, 10 

End Sub 

Public Sub MakeBold(startPos As Integer, charCount As Integer) 
    With ActiveCell.Characters(start:=startPos, length:=charCount).Font 
     .Name = "Arial" 
     .FontStyle = "Bold" 
     .Size = 10 
     .Strikethrough = False 
     .Superscript = False 
     .Subscript = False 
     .OutlineFont = False 
     .Shadow = False 
     .Underline = xlUnderlineStyleNone 
     .ColorIndex = xlAutomatic 
    End With 
End Sub 
+0

因此,如果在电子表格中,我的小区设置为 = GENERATE_STAFFING_SECTION(.....)我该如何根据内容去格式化文本? – achinda99 2009-09-10 15:47:49

+0

+1:非常酷的部分显示格式Sk93。我一直想知道部分是如何完成的。 – RBarryYoung 2009-09-10 15:53:18

+0

而没有写完整的代码,你知道“任务名称”将从1开始并滚到第一个换行,所以使用“Instr”来查找第一个换行字符。您现在将在上面的代码中使用taskname的开始和结束点。 接下来,您知道“Lead:”是来自您已有的换行符,并且它的长度为五个字符...您是下一个合作伙伴。 等等:) – Sk93 2009-09-10 15:54:07

相关问题