Search code examples
excelvbauserform

excel userform sum


I need to sum a column but I don't know how to select a range. For example I have 10 rows in a column; when I press CommandButton5 (where I have a texbox and I enter 10) my code tries to sum numbers. After another 15-20 rows, I need again to sum numbers, but I need the last 15-20. How I can to do this?

Private Sub CommandButton5_Click()

Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets(ComboBox1.Value)
Dim n As Long
Dim total As Long
n = sh.Range("A" & Application.Rows.Count).End(xlUp).Row 'Adaugare rand nou

    total = Application.WorksheetFunction.Sum(sh.range("O" & n-me.sfarsitdeluna.value):Sh.range("O" & n).value)

End Sub

I'm working in userform in excel, but I don't know why my code doesn't recognize :.


Solution

  • Your code isn't recognizing the : colon because it's not passing the argument to the Sum function in the expected format. Try creating a string variable for the range address then pass that to the function, something like this:

    Dim sRangeToSum as String
    sRangeToSum = "O" & n-me.sfarsitdeluna.value & ":O" & n
    total = Application.WorksheetFunction.Sum(sh.range(sRangeToSum))