[英]Excel VBA add border if active cell on certain row
我正在為甘特圖電子表格編寫一些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
此行不執行您認為的操作: 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
在代碼中進一步講解。
[ 更新:讓-弗朗索瓦·科貝特(Jean-FrançoisCorbett)已更正您的代碼邏輯:檢查活動單元格是否在第6行中。但是使用錯字時,代碼不會產生上下邊界。
您的代碼無法編譯。 請考慮在代碼模塊頂部使用Option Explicit
。 我可以復制您的問題的唯一方法是刪除Option Explicit
。 我設置了VBA編輯器,以便它自動將Option Explicit
放在新模塊的頂部。
LineStyle屬性必須是XlLineStyle常量之一:
在您的代碼中,您編寫的xlContinuos不是xlContinuous 。 進行此更正后,代碼應該可以正常工作。
同樣,這只是次要點,但從技術上講,Worksheet_Change事件應聲明如下:
Private Sub Worksheet_Change(ByVal Target As Range)
我是否可以建議您利用VBA編輯器的內置功能以及幫助文檔?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.