Excel宏应用公式但不评估它

时间:2017-04-22 16:36:29

标签: excel vba excel-vba

我想使用我的宏将一个简单的公式应用到我的工作表R列的每一行,评估C列中的相应单元格 公式很简单:

=YEAR(C2)

当C2将更新为C3,C4 ...在正确的行中。宏中的行是

sca.Range("R2:R" & fA2 + fA1 + fA0).Formula = formx

并且我的字符串变量sca

正确地在我的工作表formx中编写了公式

宏写入公式,但不执行计算。出现#NAME错误消息。也没有使用one of other methods suggested here作品进入ENTER。但是如果我在近列(或通过自动编写的公式)手动编写相同的公式,它可以正常显示年份。 当宏应用时,即使=YEAR(Sheet1!C2)也不起作用。

编辑:sktneer要求的完整代码。

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 

1 个答案:

答案 0 :(得分:0)

单元格可以格式化为文本。尝试将单元格的格式更改为常规:

With sca.Range("R2:R" & fA2 + fA1 + fA0)
    .Cells.NumberFormat = "General"
    .Formula = formx
End With