Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum values from one Worksheet in another Worksheet #vba

I am trying to sum values from my original worksheet in specific cells in my newly created worksheet, which has a template to fill out.
When I used macro recorder, it references the worksheet name, which would not be useful as the worksheet name changes depending on which worksheet I am working in when I run the code.
So I tried changing the worksheet name to a variable "XCXX".
The first argument works so I thought everything was okay, however, on the second argument, it keeps trying to open a file, when it should simply go back to XCXX and pull the values.
Is it a problem with my activesheet changing?

Sub AddWorkbooks()

Dim ChangeOrder As Range
Dim XCXX As Worksheet
Dim CoForm As Worksheet

Set XCXX = ActiveSheet
Set CoForm = Worksheets("+CO Form+")
'Set wbNew = Workbooks.Add

CoForm.Copy After:=Sheets(ActiveSheet.Index)

With CoForm
    Range("A6:D6").Select
    ActiveCell.FormulaR1C1 = XCXX.Range("D2").Value
    Range("AD81").Select
    ActiveCell.FormulaR1C1 = "='XCXX'!R[-64]C[-24]+'XCXX'!R[-64]C[-23]"
    
End With

End Sub

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This should be close:

Sub AddWorkbooks()

    Dim ChangeOrder As Range
    Dim XCXX As Worksheet, wb As Workbook
    Dim CoForm As Worksheet, CoFormCopy As Worksheet
    
    Set wb = ActiveWorkbook
    Set XCXX = ActiveSheet
    Set CoForm = wb.Worksheets("+CO Form+")
    
    CoForm.Copy After:=XCXX
    Set CoFormCopy = XCXX.Next 'the copy of "+CO Form+"
    
    With CoFormCopy 'assuming you want to work with the copy?
        .Range("A6:D6").Value = XCXX.Range("D2").Value
        .Range("AD81").FormulaR1C1 = _
           Replace("='<nm>'!R[-64]C[-24]+'<nm>'!R[-64]C[-23]", "<nm>", XCXX.Name)
    End With

End Sub

Note when using With you need to use a period to link (eg) Range() with the object used in the With statement, otherwise it defaults to the active sheet.

Also generally there’s no need to select a range to do something with it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading