前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >VBA代码:在工作表中自动添加矩形

VBA代码:在工作表中自动添加矩形

作者头像
fanjy
发布2024-04-26 15:49:21
420
发布2024-04-26 15:49:21
举报
文章被收录于专栏:完美Excel完美Excel

excelperfect

标签:VBA

这是在www.wimgielis.com中看到的一段代码,可以在工作表中自动添加一个矩形,用户可以指定矩形的大小和填充的颜色,以及指定相关联的宏。辑录于此,供参考。

VBA代码如下:

代码语言:javascript
复制
Sub Add_Macro_Rectangle()
 Dim ws                    As Worksheet
 Dim sh                    As Object
 Dim sText                 As String
 Dim sDimensions           As String
 Dim rDimensions           As Range
 Dim iColor                As Integer
 Dim s As String

 On Error Resume Next

 Set ws = ActiveSheet
 sDimensions = Trim(Application.InputBox("请输入形状的大小 (行 x 列)", "形状大小", "3x3", , , , , 2))
 iColor = Trim(Application.InputBox("请输入形状的颜色: 1 =蓝色, 2 =绿色, 3 =红色", "形状的填充颜色", "2", , , , , 1))
 iColor = WorksheetFunction.Min(iColor, 3)
 iColor = WorksheetFunction.Max(iColor, 0)
 Set rDimensions = Selection.Cells(1).Resize(CDbl(Split(sDimensions, "x")(0)), CDbl(Split(sDimensions, "x")(1)))
 
 With rDimensions
   Set sh = ws.Shapes.AddShape(msoShapeRoundedRectangle, .Left, .Top, .Width, .Height)
 End With
 
 With sh
   .Name = "Run_macro"
   '水平居中
   With .TextFrame2.TextRange.Characters(1, Len(sText)).ParagraphFormat
     .FirstLineIndent = 0                 '水平居中
     .Alignment = msoAlignCenter
   End With
   '垂直居中
   With .TextFrame2
     .VerticalAnchor = msoAnchorMiddle    '垂直居中
   End With
   With .Fill
     .ForeColor.RGB = Choose(iColor, RGB(0, 176, 240), RGB(146, 208, 80), RGB(255, 0, 0))
     .Transparency = 0
     .Solid
   End With
   With .Line
     .ForeColor.RGB = sh.Fill.ForeColor.RGB
     .Transparency = sh.Fill.Transparency
   End With
   .Placement = xlMove  'xlMoveAndSize = 1, xlMove = 2, xlFreeFloating = 3
   .Select
   Application.Dialogs(xlDialogAssignToObject).Show
 
   s = Split(.OnAction, "!")(1)
   If Len(s) = 0 Then s = .OnAction
 
   sText = Trim(Application.InputBox("请输入形状中的文本", "形状文本", s, , , , , 2))
   If sText = "False" Or Len(sText) = 0 Then sText = "添加标题"
 
   With .TextFrame.Characters
     .Text = sText
     .Font.Color = vbWhite
     .Font.Bold = True
   End With
   rDimensions.Cells(1).Select
 End With
 On Error GoTo 0
 Set ws = Nothing
End Sub

欢迎在下面留言,完善本文内容,让更多的人学到更完美的知识。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2024-04-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 完美Excel 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档