Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

excel - Border around each cell in a range

I am trying to create a simple function that will add borders around every cell in a certain range. Using the wonderful recording this generates a ton of code which is quite useless. The code below will display a 'table' of data, around each cell in this range I would like to add a border. Online I haven't been able to find a simple or clear answer for this.

All help is much appreciated!

Set DT = Sheets("DATA")
endRow = DT.Range("F" & Rows.Count).End(xlUp).Row
result = 3

For I = 2 To endRow
    If DT.Cells(I, 6).Value = Range("B1").Value Then
        Range("A" & result) = DT.Cells(I, 6).Value
        Range("B" & result) = DT.Cells(I, 1).Value
        Range("C" & result) = DT.Cells(I, 24).Value
        Range("D" & result) = DT.Cells(I, 37).Value
        Range("E" & result) = DT.Cells(I, 3).Value
        Range("F" & result) = DT.Cells(I, 15).Value
        Range("G" & result) = DT.Cells(I, 12).Value
        Range("H" & result) = DT.Cells(I, 40).Value
        Range("I" & result) = DT.Cells(I, 23).Value
        result = result + 1
    End If
Next I
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You only need a single line of code to set the border around every cell in the range:

Range("A1:F20").Borders.LineStyle = xlContinuous

It's also easy to apply multiple effects to the border around each cell.

For example:

Sub RedOutlineCells()
    Dim rng As Range

    Set rng = Range("A1:F20")

    With rng.Borders
        .LineStyle = xlContinuous
        .Color = vbRed
        .Weight = xlThin
    End With
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...