Sum function in VBA

后端 未结 4 929
长情又很酷
长情又很酷 2020-11-30 12:22

I have a problem with summing cells in vba. I need to use Cells(a,b):

Range(\"A1\").function=\"=SUM(Range(Cells(2,1),Cells(3,2)))\"

but it

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 13:18

    Place the function value into the cell

    Application.Sum often does not work well in my experience (or at least the VBA developer environment does not like it for whatever reason).

    The function that works best for me is Excel.WorksheetFunction.Sum()

    Example:

    Dim Report As Worksheet 'Set up your new worksheet variable.
    Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.
    
    Report.Cells(11, 1).Value = Excel.WorksheetFunction.Sum(Report.Range("A1:A10")) 'Add the function result.
    

    Place the function directly into the cell

    The other method which you were looking for I think is to place the function directly into the cell. This can be done by inputting the function string into the cell value. Here is an example that provides the same result as above, except the cell value is given the function and not the result of the function:

        Dim Report As Worksheet 'Set up your new worksheet variable.
        Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.
    
        Report.Cells(11, 1).Value = "=Sum(A1:A10)" 'Add the function.
    

提交回复
热议问题