You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

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 = 1 which isn't how Select Case works—you don't need to re-reference the variable in each Case. Plus, you were reassigning y = 2 inside the first Case block, which completely broke the logic flow.
  • Mismatched Variable Type: InputBox returns a string, but you declared y as a Long (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 Select statement to close the Select Case block, and there was a typo in Case 3 (using chtcolor02 instead of chtcolor03). 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 = 1 to Case Is = 1 (you could also just write Case 1 for simplicity), removed the incorrect y = 2 assignment inside the Case block, and added the missing End Select.
  • Adjusted Variable Type: Declared Y as a String to match the return type of InputBox.
  • Corrected Color Typo: Swapped chtcolor02 to chtcolor03 in Case 3 so selecting 3 applies the blue fill as intended.
  • Added Invalid Input Handling: The Case Else block now shows a message if the user enters something other than 1, 2, or 3.
  • Cleaned Up Code Formatting: Standardized capitalization for objects like TextFrame to make the code more readable.

内容的提问来源于stack exchange,提问作者Gerald Tow

火山引擎 最新活动