如何用VBA在Excel中画直线?

希望实现的功能是:在excel中横向拉动光标选中几个单元格,执行宏之后可以在同行首尾两个单元格之间画出一条直线,起始和终止位置均在此两格的正中间。请问如何编程?谢谢!
本人VBA小白,不知道能否将函数简化为亦如C的编程思路,如:1.通过交互,读入首尾单元格地址;(在表格中已经选中单元格,执行宏后自动提取首尾地址)2.将地址带入画线语句中;3.通过行高列宽数值计算直线首尾位置。

AddLine 方法

当本方法应用于 Shapes 对象时,返回一个 Shape 对象,该对象代表工作表中的新线条。当本方法应用于 CanvasShapes 对象时,返回一个 Shape 对象,该对象代表绘图画布中的新线条。

语法:
expression.AddLine(BeginX, Beginy, EndX, EndY)
其中:
expression 必选。该表达式返回 Shapes 对象。
BeginX, BeginY Single 类型,必需。相对于文档的左上角,以磅为单位给出线条的起点位置。
EndX, EndY Single 类型,必需。相对于文档的左上角,以磅为单位给出线条的终点位置。

示例:
本示例向 myDocument 中添加蓝色的虚线。

Set myDocument = Worksheets(1)
With myDocument.Shapes.AddLine(10, 10, 250, 250).Line
.DashStyle = msoLineDashDotDot
.ForeColor.RGB = RGB(50, 0, 128)
End With
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-04-23
ActiveSheet.DrawingObjects.Delete
Dim startdate As Date, enddate As Date
Dim l As Single, t As Single, r As Single, sh As Shape
For i = 5 To 24
If Cells(i, 3) > "" Then
startdate = CDate(Replace(Split(Cells(i, 3), "-")(0), ".", "-"))
enddate = CDate(Replace(Split(Cells(i, 3), "-")(1), ".", "-"))
t = (Cells(i, 1).Top + Cells(i + 1, 1).Top) / 2
l = Cells(i, 4 + DateDiff("m", #9/1/2008#, startdate)).Left + Day(startdate) * Cells(i, 4).Width / Day(DateSerial(Year(startdate), Month(startdate) + 1, 0))
r = Cells(i, 4 + DateDiff("m", #9/1/2008#, enddate)).Left + Day(enddate) * Cells(i, 4).Width / Day(DateSerial(Year(enddate), Month(enddate) + 1, 0))
Set sh = ActiveSheet.Shapes.AddLine(l, t, r, t)
sh.Line.Weight = 1.8
sh.Line.ForeColor.RGB = Int(Rnd * &HFFFFFF)
End If
Next

你看看,是否可以学会划线呢
相似回答