1

我正在为甘特图电子表格编写一些 VBA。

我在第 5 行有 3 个月的日期,我可以通过在更新整个工作表的单元格中输入日期来设置开始日期。

我的图表 L6:CZ42 有一系列单元格。对于此范围,如果第 5 行中的单元格是该月的 1 号,则该列中的每个单元格都将有一个灰色虚线左边框,而右侧没有任何内容。这可以按我的意愿工作。

问题是它在单元格的顶部和底部添加了一个灰色边框,这对于第 7 到 41 行是可以的,但是对于第 6 行,我想要一个黑色的顶部边框,而对于第 42 行,我想要一个黑色的底部边框。

我添加了这部分代码试图对这个问题进行排序,但语法错误,检查它是否在第 6 行

' If this is the first row (6) in the range then
' add a black continuous border to the top
If Cells(6, i) Then
    With .Borders(xlEdgeTop)
        .ColorIndex = 1
        .Weight = xlThin
        .LineStyle = xlContinuos
    End With
End If

这是我的全部代码

Sub Worksheet_Change(ByVal Target As Range)

Dim i As Long
Dim CuDate As Date


For i = 12 To 104
CuDate = Cells(5, i).Value

' Are we on the 1st day of the month
If Day(CuDate) = 1 Then
    With Range(Cells(6, i), Cells(42, i))
        ' If this is the first row (6) in the range then
        ' add a black continuous border to the top
        If Cells(6, i) Then
            With .Borders(xlEdgeTop)
                .ColorIndex = 1
                .Weight = xlThin
                .LineStyle = xlContinuos
            End With
        End If

        With .Borders(xlEdgeLeft)
            .ColorIndex = 15
            .Weight = xlThin
            .LineStyle = xlDot
        End With
        With .Borders(xlEdgeRight)
            .LineStyle = xlLineStyleNone
        End With
    End With
Else
    With Range(Cells(6, i), Cells(42, i))
        ' If this is the last row (42) in the range then
        ' add a black continuous border to the bottom
        If Cells(42, i) Then
            With .Borders(xlEdgeBottom)
                .ColorIndex = 1
                .Weight = xlThin
                .LineStyle = xlContinuos
            End With
        End If

        With .Borders(xlEdgeLeft)
            .LineStyle = xlLineStyleNone
        End With
        With .Borders(xlEdgeRight)
            .LineStyle = xlLineStyleNone
        End With
    End With
End If

Next
End Sub
4

2 回答 2

6

这条线没有做你认为它做的事情:If Cells(6, i) Then

这相当于说:If Cells(6, i).Value = True Then,即“如果第 6 行和第 6 列的单元格内容i计算为True当隐式强制为布尔值时,则”,这显然不是您想要的。相反,请尝试:

If ActiveCell.Row = 6 Then

同样的推理If Cells(42, i) Then在您的代码中也适用。

于 2012-05-23T10:18:16.343 回答
2

[更新: Jean-François Corbett 已经更正了您的代码逻辑:检查活动单元格是否在第 6 行。但是由于拼写错误,代码不会产生顶部和底部边框。]

您的代码无法编译。请考虑Option Explicit在代码模块的顶部使用。我可以复制您的问题的唯一方法是删除Option Explicit. 我设置了 VBA 编辑器,使其自动放置Option Explicit在新模块的顶部。

LineStyle 属性必须是XlLineStyle常量之一:

  • xl连续
  • xlDash
  • xlDashDot
  • xlDashDotDot
  • xl点
  • xl双
  • xlSlantDashDot
  • xlLineStyleNone

在您的代码中,您写的是 xlContinuos而不是xlContinuos。进行此更正后,代码应该可以工作。

此外,这是一个小问题,但从技术上讲,Worksheet_Change 事件应声明如下:

Private Sub Worksheet_Change(ByVal Target As Range)

我可以建议您利用 VBA 编辑器的内置功能以及帮助文档吗?

于 2012-05-23T20:42:11.513 回答