Excel VBA添加边框,如果某些行上的活动单元格
我正在为甘特图电子表格写一些VBA。
我在第5行有3个月的date价值,我可以通过在更新整个工作表的单元格中inputdate来设置开始date。
我有一个单元格的范围为我的图表L6:CZ42。 对于这个范围,如果第5行的单元格是月份的第一个,则该列中的每个单元格将具有灰色虚线的左边框,而右边没有任何内容。 这工作如何我想要的。
问题是,它增加了一个灰色边框的单元格的上方和底部,行7到41是好的,但行6我想要一个黑色的顶部边框和行42我想要一个黑色的底部边框。
我添加了这段代码试图sorting这个问题,但语法错误检查是否在第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
这条线不会做你认为的事情: If Cells(6, i) Then
这相当于说: If Cells(6, i).Value = True Then
,即“如果行6和列i
上的单元格内容在隐式强制为布尔值时评估为True
”,那么显然不是你想要的。 相反,请尝试:
If ActiveCell.Row = 6 Then
If Cells(42, i) Then
的原因相同If Cells(42, i) Then
在代码中进一步下降。
[ 更新: Jean-FrançoisCorbett已经纠正了您的代码逻辑:检查活动单元格是否在第6行。但是对于错字,代码不会产生顶部和底部边框。]
你的代码不能编译。 请考虑在代码模块的顶部使用Option Explicit
。 我可以复制您的问题的唯一方法是通过删除Option Explicit
。 我设置了VBA编辑器,以便自动将Option Explicit
放置在新模块的顶部。
LineStyle属性必须是XlLineStyle常量之一:
- xlContinuous
- xlDash
- xlDashDot
- xlDashDotDot
- xlDot
- xlDouble
- xlSlantDashDot
- xlLineStyleNone
在你的代码中,你写了xlContinuos而不是xlContinuous 。 一旦你做了这个更正的代码应该工作。
此外,这是一个小问题,但从技术上说Worksheet_Change事件应声明如下:
Private Sub Worksheet_Change(ByVal Target As Range)
我可以build议您利用VBA编辑器的内置function以及帮助文档吗?