Consulting

Results 1 to 4 of 4

Thread: Using Sumif in a Macro

  1. #1

    Using Sumif in a Macro

    I am trying to write a macro to sum the information below onto another page based upon the "pre contract condition". Meaning i want to sum all of "base contract" into one row with the each of the following columns summed so that in the end it appears on the new sheet like the bottom column. My problem is that besides "base contract" the contract condition entries are not static. My question is how do i do a "sumif" with the data based upon an undefined number of conditions and returned the summed result? I have not written a macro like this before and am not sure where to start. (data is attached)

  2. #2
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    Hi Jason,
    Welcome to VBAX

    Give this a try
    [VBA]
    Sub Macro1()
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim Rng As Range

    Set sh1 = Sheets(1)
    Set sh2 = Sheets(2)
    Set Rng = Range(sh1.Cells(1, 1), sh1.Cells(Rows.Count, 1).End(xlUp))

    sh1.Range("A1:G1").Copy sh2.Range("A1")
    Rng.AdvancedFilter Action:=xlFilterCopy, CopyToRange:=sh2.Range("A1"), Unique:=True
    Set Rng = Range(sh2.Cells(2, 1), sh2.Cells(Rows.Count, 1).End(xlUp))
    Rng.Offset(, 1).Resize(, 6).FormulaR1C1 = "=SUMIF(Sheet1!C1,Sheet2!RC1,Sheet1!C)"
    End Sub

    [/VBA]
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  3. #3
    Thanks for the response. I have copied this into my macro, but I am now getting an error message that says: "This command requires at least two rows of source data. You cannot use this command on a selection in only one row." Can you help me resolve this? Thanks for your help

  4. #4
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Do you have any data other than headings? It works on your workbook supplied.
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •