如果在Excel中满足条件,如何在两个单元格之间绘制虚线

时间:2016-08-10 12:30:15

标签: excel excel-vba macros excel-formula vba

我的Excel文件如下所示:

enter image description here

如果满足某个条件,我如何在单元格(xxxx)和单元格(aaa)之间绘制红色虚线?

2 个答案:

答案 0 :(得分:2)

以下是如何在两个Range之间画一条线并将其格式化的示例,例如:红色和虚线。您可以根据应用程序所需的条件调整测试代码以选择两个Range。请注意,测试代码使用左侧为rng1且右侧为rng2的假设:

Option Explicit

Sub Test()

    Dim rng1 As Range
    Dim rng2 As Range

    'assume L->R line where rng1 is left and rng2 is right
    'you can set these ranges based on any logic you have
    Set rng1 = Sheet1.Range("B2")
    Set rng2 = Sheet1.Range("G5")

    DrawLineBetweenCells rng1, rng2

End Sub

Sub DrawLineBetweenCells(rng1 As Range, rng2 As Range)

    Dim sngBeginX As Single
    Dim sngBeginY As Single
    Dim sngEndX As Single
    Dim sngEndY As Single
    Dim ws As Worksheet
    Dim shp As Shape

    'get worksheet of source range (assume target is same sheet...)
    Set ws = rng1.Parent

    'right middle edge of start cell
    sngBeginX = rng1.Left + rng1.Width
    sngBeginY = rng1.Top + (rng1.Height / 2)

    'left middle edge of end cell
    sngEndX = rng2.Left
    sngEndY = rng2.Top + (rng1.Height / 2)

    'draw line
    Set shp = ws.Shapes.AddLine(sngBeginX, sngBeginY, sngEndX, sngEndY)

    'format line
    shp.Line.ForeColor.RGB = RGB(255, 0, 0)
    shp.Line.EndArrowheadStyle = msoArrowheadDiamond
    shp.Line.DashStyle = msoLineDash

End Sub

示例:

enter image description here

答案 1 :(得分:1)

使用带有公式的条件格式并将边框格式化为底部。 你不能格式化单元格的内部,只能在外面格式化,所以要牢记这一点。