0

i am trying to insert a formula in a cell using vba using a dynamic column reference like this:

Fred = ConvertToLetter(ActiveCell.Column)
Bob = "=DATE(LEFT(" + Fred + "2,4),MID(" + Fred + "2,5,2),MID(" + Fred + "2,7,2))"
ActiveCell.FormulaR1C1 = Bob    

Function ConvertToLetter(iCol As Integer) As String
    Dim iAlpha As Integer
    Dim iRemainder As Integer
    iAlpha = Int(iCol / 27)
    iRemainder = iCol - (iAlpha * 26)
    If iAlpha > 0 Then
        ConvertToLetter = Chr(iAlpha + 64)
    End If
    If iRemainder > 0 Then
        ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
    End If
End Function

but when it runs the formula ends up with single quotes around the cell and the formula does not work like this:

=DATE(LEFT('AY2',4),MID('AY2',5,2),MID('AY2',7,2))

how do i stop the single quotes being added to allow the formula to work correctly?

Thanks

2
  • there is also a more elegant function to find the column letter here Commented Sep 10, 2015 at 15:12
  • Don't know if it really matters, but you really ought to use the ampersand not plus sign for string concatenation. Commented Sep 11, 2015 at 2:14

3 Answers 3

1

It's the FormulaR1C1 property causing the problem.

Do this instead:

ActiveCell.Formula = Bob

By the way, instead of the ConvertToLetter() function, you can use this:

Fred = Split(ActiveCell.Address, "$")(1)
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent works a treat, trying to be clever and reusing a recorded macro that where the R1C1 came from....
0

You can use this '' (two single apostrophes) instead.

Comments

0

To use R1C1 formula you'd use:

ActiveCell.FormulaR1C1 = "=DATE(LEFT(R2C,4),MID(R2C,5,2),MID(R2C,7,2))"

R2 in the formula means Row 2. C in the formula means the column the formula is in.

Looking at R1C1 notation:
R[-1] means this row minus 1.
C[1] means this column plus 1.
R1 means row 1
C1 means column 1
R means this row.
C means this column.

So, in cell B2 - R1C1 means cell A1.
R1C[-1] means cell A1
RC1 means cell A2.
RC means cell B2.

Hope that's clear. :)

or you can just use ActiveCell.Formula = Bob as Excel Hero said.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.