我有一个关于选择三角形的问题 我知道我可以通过这段代码选择对角线:
Sub SelectDiagonal()
a = Selection.Row()
b = Selection.Column()
c = Selection.Rows.Count
d = Selection.Columns.Count
Dim Rng As Range
Set Rng = Cells(a + c - 1, b)
For i = 1 To c - 1
Set Rng = Union(Rng, Cells(a + c - 1 - i, b + i))
Next
Rng.Select
End Sub
但是,我想选择所有向下三角形 我想要的是选择黄色单元格,如下图。
我试过这段代码:
Sub SelectDownTriangle()
a = Selection.Row()
b = Selection.Column()
c = Selection.Rows.Count
d = Selection.Columns.Count
For i = 1 To c - 1
For j = 1 To i
Cells(a + i, b + d - j).Select
Next
Next
End Sub
但它不起作用。
有任何帮助吗?谢谢
[编辑]
在@ Vityata的回答中,我编辑了代码:
Sub SelectDownTriangle()
Dim a As Long, b As Long, c As Long, d As Long
Dim i As Long
a = Selection.Row()
b = Selection.Column()
c = Selection.Rows.Count
d = Selection.Columns.Count
Dim lastCol As Long
Dim Rng As Range
Set Rng = Cells(a + c - 1, b + 1)
For i = 1 To c - 1
Set Rng = Union(Rng, Cells(a + c - 2 - i, b + i + 1))
If Cells(a + c - 2 - i, b + i + 1).Column > lastCol Then
lastCol = Cells(a + c - 2 - i, b + i).Column
End If
Next
Dim colCounter As Long
Dim myCell As Range
For Each myCell In Rng
For colCounter = myCell.Column To lastCol
Cells(myCell.Row, colCounter).Interior.Color = vbGreen
Next colCounter
Next myCell
End Sub
答案 0 :(得分:1)
使用你的代码,你需要一个循环,它可以循环rng
到最后一列的每个单元格,并用颜色填充它:
Option Explicit
Sub SelectDiagonal()
Dim a As Long, b As Long, c As Long, d As Long
Dim i As Long
a = Selection.row()
b = Selection.Column()
c = Selection.Rows.Count
d = Selection.Columns.Count
Dim lastCol As Long
Dim Rng As Range
Set Rng = Cells(a + c - 1, b)
For i = 1 To c - 1
Set Rng = Union(Rng, Cells(a + c - 1 - i, b + i))
If Cells(a + c - 1 - i, b + i).Column > lastCol Then
lastCol = Cells(a + c - 1 - i, b + i).Column
End If
Next
Dim colCounter As Long
Dim myCell As Range
For Each myCell In Rng
For colCounter = myCell.Column To lastCol
Cells(myCell.row, colCounter).Interior.Color = vbGreen
Next colCounter
Next myCell
End Sub