我正在尝试将VBA的查找功能用于动态范围。下图是我尝试测试的几行数据的示例。前两行是我的标题行,表示每年“可用数据”的“高度”范围。
黑色字体数据是我的行数据。从代码处获取红色字体数据,该红色字体数据仅是该高度的所有可用年份的每个高度的最大值(即最大值)。现在我也试图用VBA中的查找函数找到最大值的年份并粘贴到右侧单元格,如图1中的蓝色字体所示。我可以使用以下代码对选定范围执行此操作并生成输出如图1所示,但我无法从逻辑上考虑如何在动态范围内执行此操作。
我的问题是,以黑色突出显示的行数据是动态范围,以红色突出显示的数据也将是动态范围,具体取决于“高度”的数量。因此,我正在努力思考一种设置黑色和红色文本两个范围的逻辑方法,并找到最大值的年份,如图1中的蓝色所示。如果有人能就如何给我一些建议我会很高兴我可以解决这个问题。提前致谢!
Sub Lookup()
Range("K3").Select
ActiveCell.FormulaR1C1 = _
"=LOOKUP(RC[-3],RC[-10]:RC[-4],R[-1]C[-10]:R[-1]C[-4])"
Range("K3").Select
ActiveCell.FormulaR1C1 = "=LOOKUP(RC[-3],RC1:RC7,R2C1:R2C7)"
Range("K3").Select
Selection.AutoFill Destination:=Range("K3:M3"), Type:=xlFillDefault
Range("K3:M3").Select
Selection.AutoFill Destination:=Range("K3:M5"), Type:=xlFillDefault
Range("K3:M5").Select
End Sub
答案 0 :(得分:0)
这不完全是你要去的,但是因为我已经完成并测试了它。工作,它可以提供您想要的结果,并允许以后输入更多年。
Private Sub FilterMax()
Dim max10 As Single
Dim max20 As Single
Dim max30 As Single
Dim max10Year As Long
Dim max20Year As Long
Dim max30Year As Long
Dim row As Long
Dim lastRow As Long
Dim firstYear As Long
Dim lastYear As Long
Dim year As Long
Dim sheet As String
lastRow = Sheets("MaxValues").Range("A" & Rows.Count).End(xlUp).row
'You might want to put an input box up or just manually set this.
firstYear = 2012
lastYear = 2014
For row = 2 To lastRow
'reset max for each DataRow
max10 = 0
max10Year = 0
max20 = 0
max20Year = 0
max30 = 0
max30Year = 0
For year = firstYear To lastYear
sheet = CStr(year)
'Max10
If Sheets(sheet).Cells(row, 2) > max10 Then
max10 = Sheets(sheet).Cells(row, 2)
max10Year = Sheets(sheet).Range("G1")
End If
'Max20
If Sheets(sheet).Cells(row, 3) > max20 Then
max20 = Sheets(sheet).Cells(row, 3)
max20Year = Sheets(sheet).Range("G1")
End If
'Max30
If Sheets(sheet).Cells(row, 4) > max30 Then
max30 = Sheets(sheet).Cells(row, 4)
max30Year = Sheets(sheet).Range("G1")
End If
Next year
Sheets("MaxValues").Cells(row, 2).Value = max10
Sheets("MaxValues").Cells(row, 2).Font.Color = vbRed
Sheets("MaxValues").Cells(row, 3).Value = max10Year
Sheets("MaxValues").Cells(row, 3).Font.Color = vbBlue
Sheets("MaxValues").Cells(row, 4).Value = max20
Sheets("MaxValues").Cells(row, 4).Font.Color = vbRed
Sheets("MaxValues").Cells(row, 5).Value = max20Year
Sheets("MaxValues").Cells(row, 5).Font.Color = vbBlue
Sheets("MaxValues").Cells(row, 6).Value = max30
Sheets("MaxValues").Cells(row, 6).Font.Color = vbRed
Sheets("MaxValues").Cells(row, 7).Value = max30Year
Sheets("MaxValues").Cells(row, 7).Font.Color = vbBlue
Next row
End Sub