我想用我的宏來將一個簡單的公式應用於列R中的每一行,評估C列中的相應單元格。公式很簡單:Excel宏應用公式,但不要評估它
=YEAR(C2)
時,C2將正確的行中更新到C3,C4 ......。在宏行是
sca.Range("R2:R" & fA2 + fA1 + fA0).Formula = formx
和式是從我的字符串變量formx
宏寫入式正確地寫在我的片sca
,但不進行計算。出現#NAME錯誤訊息。既沒有按ENTER鍵也沒有使用one of other methods suggested here作品。但是如果我在近欄中(或通過自動編寫的公式)手工編寫相同的公式,它將起作用:年份正確顯示。 即使=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
什麼是您的宏?什麼是「formx」? – BruceWayne
在將它分配給.Formula之前,我會仔細查看formx的內容。那裏可能有CR或LF嗎?還是其他一些特殊字符?如何一堆空間和一些其他文字? –
在應用公式之前使用Debug.Print formx或MsgBox formx,並檢查該字符串是否與真正的Excel公式相同。否則,如果拼錯一個公式,可能會發生#NAME錯誤。 – sktneer