新浪博客

excel VBA添加图形对象,使用AddShape方法

2012-09-15 07:57阅读:
如果需要在工作表中添加图形对象,可以使用AddShape方法,如下面的代码所示。
1. Sub AddShape()
2. Dim myShape As Shape
3. On Error Resume Next
4. Sheet1.Shapes('myShape').Delete
5. Set myShape = Sheet1.Shapes.AddShape(msoShapeRectangle, 40, 120, 280, 30)
6.
With myShape
7. .Name = 'myShape'
8. With .TextFrame.Characters
9. .Text = '单击将选择Sheet2!'
10. With .Font
11. .Name = '华文行楷'
12. .FontStyle = '常规'
13. .Size = 22
14. .ColorIndex = 7
15. End With
16. End With
17. With .TextFrame
18. .HorizontalAlignment = -4108
19. .VerticalAlignment = -4108
20. End With
21. .Placement = 3
22. End With
23. myShape.Select
24. With Selection.ShapeRange
25. With .Line
26. .Weight = 1
27. .DashStyle = msoLineSolid
28. .Style = msoLineSingle
29. .Transparency = 0
30. .Visible = msoTrue
31. .ForeColor.SchemeColor = 40
32. .BackColor.RGB = RGB(255, 255, 255)
33. End With
34. With .Fill
35. .Transparency = 0
36. .Visible = msoTrue
37. .ForeColor.SchemeColor = 41
38. .OneColorGradient 1, 4, 0.23
39. End With
40. End With
41. Sheet1.Range('A1').Select
42. Sheet1.Hyperlinks.Add Anchor:=myShape, Address:='', _
43. SubAddress:='Sheet2!A1', ScreenTip:='选择Sheet2!'
44. Set myShape = Nothing
45.End Sub
代码解析:
AddShape
过程在作表中添加一个矩形并设置其外观等属性。
2行代码声明变量myShape的对象类型。
34行代码删除可能存在的名称为“myShape”的图形对象。
5行代码使用AddShape方法在工作表中添加一个矩形。当该方法应用于Shapes对象时,返回一个Shape对象,该对象代表工作表中的新自选图形,语法如下:
expression.AddShape(Type, Left, Top, Width, Height)
参数expression是必需的,返回一个Shapes对象。
参数Type是必需的,指定要创建的自选图形的类型。
参数LeftTop是必需的,以磅为单位给出自选图形边框左上角的位置。
参数WidthHeight是必需的,以磅为单位给出自选图形边框的宽度和高度。
7行代码将新建图形命名为“myShape”,向Shapes集合添加新的图形时,将对新添加的图形赋以默认的名称,若要为图形指定更有意义的名称,可指定其Name属性。
8行到第16行代码为矩形添加文字,并设定其格式。
其中第8行代码使用TextFrame 属性和Characters方法返回该矩形的字符区域。应用于Shape对象的TextFrame 属性返回一个TextFrame对象,该对象包含指定图形对象的对齐和定位属性;Characters

我的更多文章

下载客户端阅读体验更佳

APP专享