问与答111:如何使用VBA画直线?

excelperfect

引言:今天的问题整理自mrexcel.com论坛,不难但可能会有部分人会感兴趣。

Q:我怎样使用VBA代码在两个单元格之间绘制一条直线?一个单元格命名为“start”,另一个单元格命名为“stop”,我想绘制一条红色的直线连接它们。如下图1所示。

图1

A:很简单的代码。

先确定直线的起点和终点坐标,再绘制直接并添加颜色。代码如下:

Sub AddLine()

Dim l1 As Long

Dim l2 As Long

Dim r1 As Long

Dim r2 As Long

With ActiveSheet.Range('start')

l1 = .Left

l2 = .Top

End With

With ActiveSheet.Range('stop')

r1 = .Left

r2 = .Top

End With

With ActiveSheet.Shapes.AddLine(l1, l2, r1,r2).Line

.ForeColor.RGB = RGB(255, 0, 0)

End With

End Sub

如果直线的起点在单元格start的左下角,如下图2所示。

图2

可以使用下面的代码:

Sub AddLine1()

Dim l1 As Long

Dim l2 As Long

Dim r1 As Long

Dim r2 As Long

With ActiveSheet.Range('start')

l1 = .Left

l2 = .Top + .RowHeight

End With

With ActiveSheet.Range('stop')

r1 = .Left

r2 = .Top

End With

With ActiveSheet.Shapes.AddLine(l1, l2, r1,r2).Line

.ForeColor.RGB = RGB(255, 0, 0)

End With

End Sub

如果直线的起点在单元格start的右下角,如下图3所示。

图3

可以使用下面的代码:

Sub AddLine2()

Dim l1 As Long

Dim l2 As Long

Dim r1 As Long

Dim r2 As Long

With ActiveSheet.Range('start')

l1 = .Left + .ColumnWidth * 6.5

l2 = .Top + .RowHeight

End With

With ActiveSheet.Range('stop')

r1 = .Left

r2 = .Top

End With

With ActiveSheet.Shapes.AddLine(l1, l2, r1,r2).Line

.ForeColor.RGB = RGB(255, 0, 0)

End With

End Sub

可以调整代码中的数值“6.5”,以确定合适的起点位置。

(0)

相关推荐