excelfor-loopcss-positionexcel-r1c1-notationvba

Excel VBA loop using relative references and needing a fixed cell in the formula


I am coding two loops. The first loop sums a column 14 times and then goes through each worksheet in the workbook until they are all calculated. The second loop is more complex. The formula, if you were to enter it manually should be =(OFFSET(N39, -1, 0, 1, 1)) / (OFFSET($N$39, -1, -1, 1, 1)). This formula should loop 13 times. Each time it calculates, it should give the percentage of a total bucket, so as an example, it could tell you that 93% of your accounts receivables are current, then 2% are 1-10 days late, then 1.5% is 11-30 days late, etc. I cannot figure out how to code the loop that is calculating the percentage of each column. Below is my code:

    Sub Totals()
      Dim LastCell As Range
        For Each e In Worksheets
            e.Activate
            Range("M1").Select
                For i = 1 To 14
                    Set LastCell = Cells(Columns.Count, ActiveCell.Column).End(xlUp)
                    LastCell.Offset(1).Value = WorksheetFunction.Sum(Range(LastCell.End(xlUp), LastCell))
                    ActiveCell.Offset(0, 1).Select
                Next i
          ActiveCell.Offset(1, 0).Select
        Next e

            For Each d In Worksheets
            d.Activate
            Range("N1").Select
                For g = 1 To 13
                    Set LastCell = Cells(Columns.Count, ActiveCell.Column).End(xlUp)
                    LastCell.Offset(1).Value = "=(Offset(N39, -1, 0, 1, 1)) / (Offset($N$39, -1, -1, 1, 1))"
                    ActiveCell.Offset(0, 1).Select
                Next g
            Next d
    End Sub

The first loop works fine. The second loop does not, however.

End result:

End Result


Solution

  • Try to alter the For Loop to the following:

    x = 1
    For g = 14 To 26
    lastrow = ActiveSheet.Cells(Rows.Count, "N").End(xlUp).Row + 1
    ActiveSheet.Cells(lastrow, g).Value = "=R[-1]C/R[-1]C[-" & x & "]"
    x = x + 1
    Next g
    

    I have now tested this and it works accordingly...