I want to use my macro to apply a simple formula to every row of my sheet at column R, evaluating the corresponding cell in column C The formula is simply:
=YEAR(C2)
when C2 will be updated into C3, C4... in the correct row. The line in the macro is
sca.Range("R2:R" & fA2 + fA1 + fA0).Formula = formx
and the formula is written correctly in my sheet sca
from my string variable formx
The macro write the formula, but the calculation is not performed. An #NAME error message comes out. Nor hitting ENTER neither using one of other methods suggested here works. But if I wrote the same formula by hand in the near column (or over the auto-written formula), it works: the year is correctly displayed.
Even =YEAR(Sheet1!C2)
does not work when applied by the macro.
EDIT: the full code as sktneer requested.
Sub myMacro()
Dim sh0 As Worksheet, sh1, sh2 As Worksheet
Dim sca As Worksheet
Dim fA0 As Long, fA1 As Long, fA2 As Long
Dim rng0, rng1, rng2 As Range
Dim Annom0 As String
Dim Annom1 As String
Dim Annom2 As String
Dim formx As String
Dim annomax() As Variant
Dim annomin() As Variant
Dim StartDate As Integer, EndDate As Integer
'extract correct names of sheets from principal sheet
Annom0 = Cells(13, 6).Value
Annom1 = Cells(13, 7).Value
Annom2 = Cells(13, 8).Value
'extract correct number of rows from secondary sheets
fA0 = Sheets(Annom0).Cells(Rows.Count, 1).End(xlUp).Row
Cells(14, 6).Value = fA0
fA1 = Sheets(Annom1).Cells(Rows.Count, 1).End(xlUp).Row
Cells(14, 7).Value = fA1
fA2 = Sheets(Annom2).Cells(Rows.Count, 1).End(xlUp).Row
Cells(14, 8).Value = fA2
Set sh0 = Sheets(Annom0)
Set sh1 = Sheets(Annom1)
Set sh2 = Sheets(Annom2)
Set sca = Sheets("GLOBAL")
'calculate the minimum and the maximum dates
annomax = sh0.Range(sh0.Cells(2, 3), sh0.Cells(fA0, 3)).Value2
annomin = sh2.Range(sh2.Cells(2, 3), sh2.Cells(fA2, 3)).Value2
Cells(15, 7).Value = CDate(Application.Max(annomax))
Cells(16, 7).Value = CDate(Application.Min(annomin))
sca.Cells.Clear
formx = "=YEAR(GLOBAL!C2)"
'create the new sheet copying all the 3 secondary sheets one bunch of rows below the other
Set rng2 = sh2.Range("A2:A" & fA2)
rng2.EntireRow.Copy sca.Cells(2, 1).End(xlUp)(2)
Set rng1 = sh1.Range("A2:A" & fA1)
rng1.EntireRow.Copy sca.Cells(fA2 + 1, 1).End(xlUp)(2)
Set rng0 = sh0.Range("A2:A" & fA1)
rng0.EntireRow.Copy sca.Cells(fA2 + fA1 + 1, 1).End(xlUp)(2)
'then reorder it
sca.Columns("A:O").Sort key1:=sca.Range("C:C"), order1:=xlAscending, Header:=xlYes
sca.Range("R2:R" & fA2 + fA1 + fA0).Formula = formx
'sca.EnableCalculation = True 'none of these method was useful
'Application.CalculateFull
'Calculate
End Sub