单元格边界的变化范围

我正在尝试在每个单元格周围放置一个边框,在FOR LOOP中循环次数由多less列包含内容决定,列数将在不同的工作表之间变化。

看起来,我不能单独在dynamic单元格的位置放置边框,而必须指定一个范围或特定的单元格。 那是对的吗?

这是我用来完成目标的代码

Sub Sheet_Formatting() For Col_Count = 1 To Col_Count_Active_Sheet ThisWorkbook.Worksheets(Active_Sheet).Cells(1, Col_Count).Interior.Color = RGB(100, 100, 100) ' sets to the color ??? ThisWorkbook.Worksheets(Active_Sheet).Cells(1, Col_Count).Borders.LineStyle.xlContinuous ' sets to the linestyle ThisWorkbook.Worksheets(Active_Sheet).Cells(1, Col_Count).Borders.Weight.xlThick ' sets to the border thickness ThisWorkbook.Worksheets(Active_Sheet).Cells(1, Col_Count).Font.Bold = True ' sets to the text format to bold Next Col_Count End Sub 

我相信有一种方法来完成边框规范,但我不能使用“单元格”来指定任何边框。 内部颜色和字体按需要工作。

Range.Borders属性和Border对象之间是有区别的。 不要混淆两者。

 Sub Sheet_Formatting() For Col_Count = 1 To Col_Count_Active_Sheet With ThisWorkbook.Worksheets(Active_Sheet).Cells(1, col_Count) .Interior.Color = RGB(100, 100, 100) ' sets to the color ??? .Borders.LineStyle = xlContinuous ' sets to the linestyle .Borders.Weight = xlThick ' sets to the border thickness .Font.Bold = True ' sets to the text format to bold End With Next Col_Count End Sub 

我已经用With … End With语句清理了一些重复的.Parent引用。 这不仅使代码更简洁,而且运行速度也更快。

您需要为边框分配属性值,就像您对“ Color和“ Bold所做的那样

 Sub Sheet_Formatting() For Col_Count = 1 To Col_Count_Active_Sheet ThisWorkbook.Worksheets(Active_Sheet).Cells(1, Col_Count).Interior.Color = RGB(100, 100, 100) ' sets to the color ??? ThisWorkbook.Worksheets(Active_Sheet).Cells(1, Col_Count).Borders.LineStyle = xlContinuous ' sets to the linestyle ThisWorkbook.Worksheets(Active_Sheet).Cells(1, Col_Count).Borders.Weight = xlThick ' sets to the border thickness ThisWorkbook.Worksheets(Active_Sheet).Cells(1, Col_Count).Font.Bold = True ' sets to the text format to bold Next Col_Count End Sub 

另外,另一种方法是:

ThisWorkbook.Worksheets(Active_Sheet).Cells(1, Col_Count).BorderAround (xlThin)