自定义函数用特定文本对行进行求和
我想总结一个可变大小的行的值:从第5列到最后一个填充单元格在第6行。
有问题的行必须在B
列中包含“ My text
”。
所以,举例来说,我想把下面的值从E8 to J8
:
这是我正在使用的代码:
Function cenas() Application.Volatile Dim celula Dim ultAno As Integer Dim intervalo As Range Dim separador As Worksheet Set separador = Sheets("Sheet1") ultAno = separador.Cells(6, 5).End(xlToRight).Column For i = 1 To 50 celula = separador.Cells(i, 2).Value If celula = "My text" Then Set intervalo = Sheets(separador).Range(Sheets(separador).Cells(i, 5), Sheets(separador).Cells(i, ultAno)) cenas = Application.Sum(intervalo) End If Next i End Function
哪个正在返回#VALUE!
我尝试了与variables声明相关的不同方法,但是找不到解决scheme。
一个问题是这条线
Set intervalo = Sheets(separador).Range(Sheets(separador).Cells(i, 5), Sheets(separador).Cells(i, ultAno))
没有必要使用Sheets()
。 separador
被设置为一张纸。
Function cenas() Application.Volatile Dim celula Dim ultAno As Integer Dim intervalo As Range Dim separador As Worksheet Set separador = Sheets("Sheet1") ultAno = separador.Cells(6, 5).End(xlToRight).Column For i = 1 To 50 celula = separador.Cells(i, 2).value If celula = "My text" Then Set intervalo = separador.Range(separador.Cells(i, 4), separador.Cells(i, ultAno)) cenas = Application.sum(intervalo) End If Next i End Function
如果你打算使用一个函数,为什么不使它更通用一点:
Function cenas(lkpStr As String) Application.Volatile Dim celula Dim ultAno As Integer Dim intervalo As Range Dim separador As Worksheet Set separador = Sheets("Sheet3") ultAno = separador.Cells(6, 5).End(xlToRight).Column For i = 7 To separador.Cell(7,2).End(xlDown).Row If separador.Cells(i, 2).value = lkpStr Then Set intervalo = separador.Range(separador.Cells(i, 5), separador.Cells(i, ultAno)) cenas = Application.sum(intervalo) End If Next i End Function Sub getsum() Dim t t = cenas("My Text") Debug.Print t End Sub
这将允许您指定要search的文本。 并返回组中最后一个的总和。 您可以在工作表或vba代码中将其称为UDF。
注意:如果B列中有多个“我的文本”,它只会返回最后一行“我的文本”。
看这样的事情。
Private Sub CommandButton34_Click() Dim ws1 As Excel.Worksheet Dim lRow As Long Dim lLastCol As Long Set ws1 = ActiveWorkbook.Sheets("Sheet1") lRow = 1 ws1.Activate 'Loop through the rows Do While lRow <= ws1.UsedRange.Rows.count If ws1.Range("B" & lRow).Value = "My text" Then 'Get the last col used in that row lLastCol = ws1.Cells(lRow, ws1.Columns.count).End(xlToLeft).Column 'Write the sum to the column after the last used column ws1.Cells(lRow, lLastCol + 1).Value = "=sum(D" & lRow & ":" & Col_Letter(lLastCol) & lRow & ")" End If lRow = lRow + 1 Loop End Sub Function Col_Letter(lngCol As Long) As String Dim vArr vArr = Split(Cells(1, lngCol).Address(True, False), "$") Col_Letter = vArr(0) End Function