2

I have gotten so much excellent help from this site. This is my first question. I have googled all the wordings I can think of and looked at all possible related threads on this site and others, and cannot find an explanation.

I am trying to automate a sheet into which a data table of variable size will be pasted.

Here is the formula I am trying to replicate:

=(C26-B26)/B26 (percent variation to previous month)

Edited to respond to a comment: This formula is in cell C28 in the sheet I am being asked to automate. So it is referring to cells two rows above and 1 column to the left of the cell where the formula is located.

Here is my code which the editor accepts:

ActiveCell.Formula = "=(" & (Cells(Index(Row() - 2), Index(Col())).Address(False, False)) & "-" & Cells(Index(Row() - 2), Index(Col() - 1)).Address(False, False) & "/" & Cells(Index(Row() - 2), Index(Col() - 1)).Address(False, False) & ")"

When I run this, I get a compile error: Sub or Function not defined and the first instance of row is highlighted.

It seems to me I read somewhere that one cannot calculate with Row() and Column() but I have not been able to find that again. I have found many examples online of people using Row() and Column() in this way to find cells adjacent to the active cell.

I appreciate any help and suggestions.

Thank you in advance.

Community
  • 1
  • 1
Amy Winter
  • 21
  • 5

1 Answers1

0

I'd determine the indices of your reference cell (the one that's not known). In the example below, I'm simply using the indices and converting them to characters from ASCII and concatenating the returned character and the row number.


    Dim activeRow, activeColumn As Integer
    activeRow = 40   'Iterate through or use Range reference as Range.Row
    activeColumn = 3 'Iterate through or use Range reference as Range.Column
    MsgBox ("=(" & Chr(64 + activeColumn) & (activeRow - 2) & "-" & Chr(64 + activeColumn - 1) & (activeRow - 2) & "/" & Chr(64 + activeColumn - 1) & (activeRow - 2) & ")")

Update: Also take a look at this question for referencing the instance of the calling cell in a Public Function, specifically Fionnuala's answer.

Community
  • 1
  • 1
tbm0115
  • 410
  • 11
  • 21
  • Thank you, I think this is a valuable alternative and I will spend time exploring it because I am sure I will encounter this situation again. – Amy Winter Aug 25 '15 at 20:22
  • Not a problem, let me know if you need further help or if this ended up working in your project. And welcome (officially) to SO! – tbm0115 Aug 25 '15 at 20:29