如何将边界添加到VBA中的多个范围?

我一直试图在两个不同的工作表上添加两个范围的边界。 在我的情况下,表一有14行,而第二个工作表有30行。 每个工作表具有相同数量的列。 当我运行我的代码时,第一个工作表正常工作,但第二个工作表只有14行是有边界的,其他16个没有边界。 为什么不是我的代码接近我的第二个工作表的最后16列?

Sub lines() Dim wb As Worksheet Dim wb2 As Worksheet Dim arrBorders As Variant, vBorder As Variant Set wb = Worksheets("wb Summary") Set wb2 = Worksheets("wb2 Summary") arrBorders = Array(xlEdgeLeft, xlEdgeTop, xlEdgeBottom, _ xlEdgeRight, xlInsideVertical, xlInsideHorizontal) With wb.Range("A2:H" & Cells(Rows.Count, "H").End(xlUp).Row) For Each vBorder In arrBorders With .Borders(vBorder) .LineStyle = xlContinuous .Weight = xlThin End With Next End With With wb2.Range("A2:H" & Cells(Rows.Count, "H").End(xlUp).Row) For Each vBorder In arrBorders With .Borders(vBorder) .LineStyle = xlContinuous .Weight = xlThin End With Next End With End Sub 

你需要充分参考工作表。 我想你也可以通过避免循环来缩短代码。

 Sub lines() Dim wb As Worksheet Dim wb2 As Worksheet Set wb = Worksheets("wb Summary") Set wb2 = Worksheets("wb2 Summary") With wb.Range("A2:H" & wb.Cells(wb.Rows.Count, "H").End(xlUp).Row) .Borders.LineStyle = xlContinuous .Borders.Weight = xlThin End With With wb2.Range("A2:H" & wb2.Cells(wb2.Rows.Count, "H").End(xlUp).Row) .Borders.LineStyle = xlContinuous .Borders.Weight = xlThin End With End Sub