
我想RangeDown在 VBA 中定義一個函式。它在第二個范圍引數中找到一個標頭,并回傳第三個范圍引數中標頭下的范圍。這是我當前的代碼:
Function RangeDown(header, range_header, range_data)
i = 0
row_header = 0
col_header = 0
For Each Cell In range_header
If Cell.Value = header Then
i = i 1
row_header = Cell.Row
col_header = Cell.Column
End If
Next Cell
If i = 0 Then
RangeDown = "Cannot find the header"
ElseIf i > 1 Then
RangeDown = "Found more than one matching headers"
Else
lastRow = range_data.Row range_data.Rows.Count - 1
If row_header >= lastRow Then
RangeDown = "No Range"
Else
Set r = Range(Cells(row_header 1, col_header), Cells(lastRow, col_header))
Set x = Application.Intersect(r, range_data)
RangeDown = x
End If
End If
End Function
一般來說,上面的代碼有效。但是,我剛剛意識到我們不能將函式ROW應用于回傳的結果RangeDown,公式如下:=LET(x, RangeDown("header4",C5:H5,C3:H9), ROW(x))#VALUE!

有誰知道如何修改 VBA 代碼以便我們可以應用于ROW結果?
uj5u.com熱心網友回復:
UDFRangeDown必須回傳一個范圍。
正如@GSerg 所說,您必須使用 SET 來回傳范圍。
另外,您必須像這樣修改公式:
=LET(x,RangeDown("header 6", C5:H5,C3:H9),IFERROR(ROW(x),x))
如果RangeDown回傳錯誤文本,ROW將失敗(IFERROR= true)并回傳 x 的結果(= 錯誤訊息)。
Function RangeDown(header As String, _
range_header As Range, _
range_data As Range) As Variant
i = 0
row_header = 0
col_header = 0
For Each Cell In range_header
If Cell.Value = header Then
i = i 1
row_header = Cell.Row
col_header = Cell.Column
End If
Next Cell
If i = 0 Then
RangeDown = "Cannot find the header"
ElseIf i > 1 Then
RangeDown = "Found more than one matching headers"
Else
lastRow = range_data.Row range_data.Rows.Count - 1
If row_header >= lastRow Then
RangeDown = "No Range"
Else
Set r = Range(range_header.Worksheet.Cells(row_header 1, col_header), range_header.Worksheet.Cells(lastRow, col_header))
Set x = Application.Intersect(r, range_data)
Set RangeDown = x
End If
End If
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/409584.html
標籤:
