select范围以应用边框 – 访问VBA

这是我需要做的。 根据行号和列号select一系列单元格。 由于它是一个dynamic的,我必须使用行和列的数字。 作为一个例子,我在这里硬编码。 一旦我有了这个范围,我需要在它周围涂上厚厚的边框。 我可以select范围。 任何帮助将不胜感激。 我已经包含了部分select代码。 我已经指出了失败的地方。

Sub setBorder() Dim xlApp As Object Dim wb As Object Dim ws As Object Dim rng As Object Dim startRow As Integer, startCol As Integer Dim endRow As Integer, endCol As Integer Set xlApp = CreateObject("Excel.Application") xlApp.DisplayAlerts = False Set wb = xlApp.Workbooks.Open("H:\Documents\Misc-Work\BU\test.xlsx") startRow = 6 startCol = 5 endRow = 15 endCol = 5 Set ws = wb.worksheets(1) With ws Set rng = .Range(.Cells(startRow, startCol), .Cells(endRow, endCol)) rng.select -- It fails here End With 'rng.select With Selection.Borders(xlEdgeLeft) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlEdgeTop) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With End Sub 

没有必要使用select:

 With ws Set rng = .Range(.Cells(startRow, startCol), .Cells(endRow, endCol)) End With With rng.Borders(7) .LineStyle = 1 .ColorIndex = 0 .TintAndShade = 0 .Weight = 2 End With With rng.Borders(8) .LineStyle = 1 .ColorIndex = 0 .TintAndShade = 0 .Weight = 2 End With 

顺便说一句, 访问不知道常量 xlEdgeLeft等,直到您添加到工具 – >参考 Microsoft Excel对象库的 引用 。 您也可以将此常量更改为其实际值,而无需像上面的代码那样添加对库的引用,但是这会使您的代码不太清晰。