VBA文本框字体颜色

时间:2017-12-28 23:10:12

标签: excel vba

我在工作中帮助更新Excel模板,我需要一些帮助。 我试图将文本框中的文本格式化为红色并删除边框。我不确定如何将该属性添加到我的代码中。我不太擅长编码。我能够通过解析我发现的其他代码将下面的内容放在一起。

ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 2525, 1800, 103, 24).TextFrame.Characters.Text = Format(Cells(9, 2), "mmmm d, yyyy")

我最终会替换文本框代码中的绝对位置值,但我希望它在我开始进行效率调整之前工作。谢谢你的帮助!

EDIT1:如果我使用第1行和第2行或第1行和第3行,下面的代码可以工作。我不确定为什么我不能同时使用这两个。

ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 2525, 1800, 103, 24) _
.TextFrame.Characters.Font.Color = vbRed _
.TextFrame.Characters.Text = Format(Cells(9, 2), "mmmm d, yyyy")

1 个答案:

答案 0 :(得分:1)

@ L L 你使用shapes.addtextbox的方式是这样的:

With ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 146#, 68#, _
        301#, 181#).TextFrame
        .Characters.Font.Color = RGB(255, 0, 0)
        .Characters.Text = "Whatever your string is"
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
 End With

enter image description here

如果我继续在文本框中输入内容,那么其余部分将以红色以及第一次分配时的内容包装,屏幕截图中的命令按钮执行上面的代码只是为了玩。

如果要继续使用代码向文本框添加和减去文本,最好是获得名为的形状。然后你可以抓住那里的字符串并添加到它。 。下面的代码显示了如何使用VBA命名然后使用文本框,添加文本等等。 。你现在可以改变文本框中某些文本的颜色,这很酷但是另一个话题可能是?

Option Explicit

Private Sub CommandButton1_Click()

Dim tbShape As Shape
Dim WKS As Worksheet
Dim newText As String
Dim previousText As String
Dim textRange As Range

Set WKS = ThisWorkbook.ActiveSheet
Set textRange = WKS.Range("C1") 'define where to grab the new text
newText = CStr(textRange) 'convert what is in the cell to string

With ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 146#, 68#, _
            301#, 181#)
            .Name = "myTextBox"
End With

Set tbShape = ActiveSheet.Shapes("myTextBox")

With tbShape.TextFrame
    .Characters.Font.Color = RGB(255, 0, 0)
    .Characters.Text = "This is the intial text of the textbox 11111111 222222 "
    .HorizontalAlignment = xlCenter
    .VerticalAlignment = xlCenter
End With

'grab the previous textbox string
previousText = tbShape.TextFrame.Characters.Text
'add your new text to what was there before
tbShape.TextFrame.Characters.Text = previousText & newText

End Sub

所以我希望这会有所帮助。如果您有开发人员选项卡,最简单的方法是添加一个ActiveX文本框(您将无法使用我认为不会使用的.characters)但您可以分配文本框名称和许多属性:文本字体,大小,颜色( .forecolor)该属性选项卡或vba中的文本框以及名称(易于制作所有颜色,很难将文本框中的选定文本更改为VBA中的某种颜色),但对于整箱?容易。

如果你这样做并希望在vba中获取文本框的内容,可以说你在代码中修改了一个注释字符串并命名你的activeX文本框TextBox1:

'get comments
comments = msrSheet.OLEObjects("TextBox1").Object.Text

enter image description here

你必须使用插入文本框的第一种方式(当前使用的方式和答案中的第一种方式),只将我选择的文本更改为新颜色。希望看到它在行动?将此代码添加到上面的内容中,但在End Sub之前,现在之前的内容是红色,如果找到,您在代码块中定义的字符串将为蓝色,在这种情况下,我懒惰地将其分配给newText

'grab the previous textbox string
previousText = tbShape.TextFrame.Characters.Text
'Change the color of the new string in the textbox to blue
Dim blueText As String
blueText = newText
With tbShape.TextFrame
    .Characters(InStr(previousText, blueText), Len(blueText)).Font.Color = RGB(0, 0, 255)
End With

enter image description here

我真诚地希望这可以帮助您寻找成为一个textBox jedi! 干杯 - WWC

相关问题