Excel 2010 VBA Referencing Specific Cells in other worksheets

excelvba

I'm sorry this is probably an extremely basic Excel VBA question. I've just started learning it, and I am not finding very much in the way of good tutorials. I can't find much organised information on the language at all actually.

I've got a couple worksheets called "Sheet1" and "Sheet2".
The first and second columns of Sheet1 contain some numbers.

I want to write a macro which prints the results of a function taking 2 variables (one each from column A and column B) to Sheet2. but I want to space these results out in the new work sheet so that the result of the function on Column 'i' in Sheet1 is put into row 1 and column 4*i. Here's what I've tried to do so far, but it hasn't worked because I don't know how to reference specific cells in other worksheets properly.

Apologies that this is a very newb question, any help is much appreciated!

Sub results()

    Dim i As Integer, noValues As Integer
    noValues = Application.CountA(Range("A:A"))

    Sheets("Sheet2").Select
    Range("A1").Select
    For i = 1 To noValues
        Range("A1").Offset(0, 4 * (i - 1)).Select
        ActiveCell.FormulaR1C1 = "=Sheet1!A[i] + Sheet1!B[i]"
    Next i

End Sub

Where A[i] and B[i] should mean the value in Column A or B, row i.

Best Solution

Sub Results2()

    Dim rCell As Range
    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim lCnt As Long

    Set shSource = ThisWorkbook.Sheets("Sheet1")
    Set shDest = ThisWorkbook.Sheets("Sheet2")

    For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
        lCnt = lCnt + 1
        shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
    Next rCell

End Sub

This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.

To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.

I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,

Sub Results3()

    Dim i As Long, lCnt As Long
    Dim sh As Worksheet

    lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
    Set sh = ThisWorkbook.Sheets("Sheet2")

    Const sSOURCE As String = "Sheet1!"

    For i = 1 To lCnt
        sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
    Next i

End Sub
Related Question