您现在使用的是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](https://istack.dev59.com/GCake.webp)
如果我在文本框中继续输入,那么剩下的内容以及与第一个赋值一起存在的任何内容都会被包含在红色中,屏幕截图中的命令按钮执行上面的代码只是为了玩耍。
如果您要使用代码不断添加和删除文本框中的文本,最好将其命名。然后,您可以抓取其中的字符串并添加到其中。以下代码显示了如何使用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),但你可以在属性选项卡或VBA中分配文本框名称和许多属性:文本字体、大小、颜色(.forecolor),以及更容易地给整个文本框设置颜色,但用这种方式改变文本框中所选文本的颜色比较困难,在VBA中需要做更多的工作。
如果你使用这种方法并且想在VBA中获取文本框的内容,假设你在代码中声明了一个字符串变量作为注释,并且你将你的ActiveX文本框命名为TextBox1:
'get comments
comments = msrSheet.OLEObjects("TextBox1").Object.Text
![enter image description here](https://istack.dev59.com/QFLhM.webp)
目前我所发现的唯一使用文本框更改选定文本颜色的方法是使用你正在使用的第一种方法(答案中的第一种方法)。 想看到它的实际效果吗? 在上面的代码后面添加以下代码,但在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
![输入图片说明](https://istack.dev59.com/LeclL.webp)
我真诚地希望这可以帮助您成为一名文本框 Jedi!祝好 - WWC