自定义函数,用于将行中的值与特定文本相加

时间:2015-10-15 19:30:46

标签: excel vba excel-vba

我想将一个变量大小的行与值相加:从第5列到第6行中最后一个填充的单元格。

相关行必须在My text列中包含“B”。

因此,例如,我想从E8 to J8中总结以下值: enter image description here

这是我正在使用的代码:

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!

我尝试了与变量声明相关的不同方法,但无法找到解决方案。

2 个答案:

答案 0 :(得分:3)

这一行有一个问题

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

这将允许您指定要搜索的文本。并返回组中最后一个的总和。您可以在工作表中或通过vba代码将其称为UDF。

注意:如果有多个"我的文字"在B列中,它只返回最后一行"我的文字"在它。

答案 1 :(得分:2)

看看这样的事情。

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