Excel 如果在这样的单元格上使用VBA函数,如何获取单元格地址?
我想在Excel表中使用VBA函数ScopeSum(),该函数检查同一行上的“1”值,然后对相关标题的值求和。Excel 如果在这样的单元格上使用VBA函数,如何获取单元格地址?,excel,vba,Excel,Vba,我想在Excel表中使用VBA函数ScopeSum(),该函数检查同一行上的“1”值,然后对相关标题的值求和。 “SopeH”是命名的标题范围。 对于100行,我必须在同一列(下例为“P”列)上使用此函数。 如果我复制函数单元格并填充所有行,结果将作为第一个单元格,但是如果我编辑它,它可以正常工作 Function ScopeSum() As String Dim i As Integer Dim j As Long Dim rng As Range Dim cur_rng As Range D
“SopeH”是命名的标题范围。
对于100行,我必须在同一列(下例为“P”列)上使用此函数。
如果我复制函数单元格并填充所有行,结果将作为第一个单元格,但是如果我编辑它,它可以正常工作
Function ScopeSum() As String
Dim i As Integer
Dim j As Long
Dim rng As Range
Dim cur_rng As Range
Dim ScopeText As String
Dim cell As Variant
Set rng = Range("ScopeH")
j = Range(ActiveCell.Address).Row
Set cur_rng = Range("ScopeH").Offset(j - 2, 0)
i = 0
ScopeText = ""
For Each cell In cur_rng.Cells
i = i + 1
If UCase(cell.Value) = 1 Then ScopeText = ScopeText & ", " & Application.WorksheetFunction.Index(rng, 1, i)
Next
ScopeSum = ScopeText
End Function
Excel表格刷新页面后
确保将数据和标题范围作为参数提交,以便UDF(用户定义函数)适用于任何数据范围并取决于数据范围。否则,如果数据发生更改,公式将不会自动更新
Option Explicit
Public Function ScopeSum(ByVal DataRange As Range, ByVal HeaderRange As Range) As String
Dim Data() As Variant ' read data into array
Data = DataRange.Value
Dim Header() As Variant ' read header into array
Header = HeaderRange.Value
Dim Result As String ' collect results for output here
Dim iCol As Long
For iCol = 1 To UBound(Data, 2) ' loop through data and concatenate headers
If Data(1, iCol) = 1 Then
Result = Result & IIf(Result <> vbNullString, ", ", vbNullString) & Header(1, iCol)
End If
Next iCol
ScopeSum = Result ' output results
End Function
确保标题已用公式中的$
符号固定。并将其复制下来:
这样做的好处是,即使范围发生变化,也不需要更改代码。您也可以通过调整公式中的范围轻松添加
项11
,而无需更改代码。确保您将数据和标题范围作为参数提交,以便UDF(用户定义函数)适用于任何数据范围,并取决于数据范围。否则,如果数据发生更改,公式将不会自动更新
Option Explicit
Public Function ScopeSum(ByVal DataRange As Range, ByVal HeaderRange As Range) As String
Dim Data() As Variant ' read data into array
Data = DataRange.Value
Dim Header() As Variant ' read header into array
Header = HeaderRange.Value
Dim Result As String ' collect results for output here
Dim iCol As Long
For iCol = 1 To UBound(Data, 2) ' loop through data and concatenate headers
If Data(1, iCol) = 1 Then
Result = Result & IIf(Result <> vbNullString, ", ", vbNullString) & Header(1, iCol)
End If
Next iCol
ScopeSum = Result ' output results
End Function
确保标题已用公式中的$
符号固定。并将其复制下来:
这样做的好处是,即使范围发生变化,也不需要更改代码。此外,只需调整公式中的范围,即可轻松添加
项目11
,而无需更改代码。非常好,这正是我需要的。谢谢,太好了,这正是我需要的。非常感谢。