夜雨聆风学习资料网

ARTICLE · 998271

使用VBA在Excel中绘图

使用VBA在Excel中绘图
学习Excel技术,关注微信公众号:
excelperfect

标签:VBA

要在Excel工作表中绘制下图1所示的形状,你会怎么做?

图1

如果你手动绘制,估计会花费大量的时间。然而,VBA能够很快搞定!详细的代码如下:

Sub DrawName()    Dim i As Integer    Dim x As Single    Dim y As Single    Dim z As Single    Dim rng As Range    Dim n As Single    Dim k As Integer    Dim sSize As Single    Dim sh As Shape    Dim sName As String    Dim StartLeft As Single    Dim StartTop As Single    StartLeft = ActiveCell.Left    StartTop = ActiveCell.Top    sName = "Welcome to excelperfect !"    n = 17    k = Len(sName)    sSize = Application.InchesToPoints(1)    For i = 1 To k        If Mid(sName, i, 1) <> " " Then            x = n * i / k            x = Application.InchesToPoints(x)            y = Application.InchesToPoints(z)            If i Mod 2 = 1 Then                Set sh = ActiveSheet.Shapes.AddShape(msoShapeUpRibbon, StartLeft + x, StartTop + y, sSize, sSize)            Else                Set sh = ActiveSheet.Shapes.AddShape(msoShapeDownRibbon, StartLeft + x, StartTop + y, sSize, sSize)            End If             sh.Fill.ForeColor.RGB = RGB(GiveRandom(150, 200), GiveRandom(200, 255), GiveRandom)            sh.Fill.Visible = msoTrue             sh.TextFrame.Characters.Text = UCase(Mid(sName, i, 1))            sh.TextFrame.Characters.Font.Size = 20            sh.TextFrame.Characters.Font.Name = "Arial"            sh.TextFrame.Characters.Font.Bold = True            sh.TextFrame.Characters.Font.Color = RGB(0, 0, 0)             sh.TextFrame2.VerticalAnchor = msoAnchorMiddle            sh.TextFrame2.TextRange.ParagraphFormat.Alignment = msoAlignCenter        End If    Next iEnd SubFunction GiveRandom(Optional lowerBound As Integer = 100, Optional upperBound As Integer = 255) As Integer     Randomize Timer    GiveRandom = Int((upperBound - lowerBound + 1) * Rnd + lowerBound)End Function

试试看。

注:本文代码整理自vitoshacademy.com,供参考。

欢迎在下面留言,完善本文内容,让更多的人学到更完美的知识。
欢迎到知识星球:完美Excel社群,进行技术交流和提问,获取更多电子资料,并通过社群加入专门的微信讨论群,更方便交流。

相关学习资料