PowerPoint VBA文本框颜色设置:Select Case代码问题求助与修正
Fixing Your PowerPoint VBA Textbox Color Selector
Let's break down why your original code wasn't working and walk through the corrected version:
What Was Wrong in the Original Code
- Incorrect Select Case Syntax: You wrote
Case y = 1which isn't how Select Case works—you don't need to re-reference the variable in each Case. Plus, you were reassigningy = 2inside the first Case block, which completely broke the logic flow. - Mismatched Variable Type:
InputBoxreturns a string, but you declaredyas aLong(numeric type). While VBA tries to convert this automatically, it's better to match types to avoid unexpected issues. - Broken Code Structure: You were missing the
End Selectstatement to close the Select Case block, and there was a typo in Case 3 (usingchtcolor02instead ofchtcolor03). Also, there was no handling for invalid inputs outside 1-3.
Corrected Working Code
Sub Insert_Textbox() Dim sld As slide, sh As shape, cursh As shape Dim Y As String Dim chtcolor01 As Long, chtcolor02 As Long, chtcolor03 As Long, w As Long, b As Long w = RGB(250, 250, 250) b = RGB(0, 0, 0) chtcolor01 = RGB(250, 0, 0) chtcolor02 = RGB(0, 250, 0) chtcolor03 = RGB(0, 0, 250) Set sld = Application.ActiveWindow.View.slide Set sh = sld.Shapes.AddShape(Type:=msoShapeRectangle, _ Left:=50, Top:=50, Width:=150, Height:=50) 'this shape will now be called sh With sh Y = InputBox("Please select a number between 1 to 3 for the color for your textboxes", "Choose your color!") Select Case Y Case Is = 1 .Fill.ForeColor.RGB = chtcolor01 .TextFrame.TextRange.Font.Color.RGB = b .Line.Visible = msoFalse 'remove border Case Is = 2 .Fill.ForeColor.RGB = chtcolor02 .TextFrame.TextRange.Font.Color.RGB = b .Line.Visible = msoFalse 'remove border Case Is = 3 .Fill.ForeColor.RGB = chtcolor03 ' Fixed the color variable typo here .TextFrame.TextRange.Font.Color.RGB = w .Line.Visible = msoFalse 'remove border Case Else MsgBox ("The number you typed is invalid, please try again") End Select End With End Sub
Key Changes Made
- Fixed Select Case Logic: Changed
Case y = 1toCase Is = 1(you could also just writeCase 1for simplicity), removed the incorrecty = 2assignment inside the Case block, and added the missingEnd Select. - Adjusted Variable Type: Declared
Yas aStringto match the return type ofInputBox. - Corrected Color Typo: Swapped
chtcolor02tochtcolor03in Case 3 so selecting 3 applies the blue fill as intended. - Added Invalid Input Handling: The
Case Elseblock now shows a message if the user enters something other than 1, 2, or 3. - Cleaned Up Code Formatting: Standardized capitalization for objects like
TextFrameto make the code more readable.
内容的提问来源于stack exchange,提问作者Gerald Tow




