![](/img/trans.png)
[英]Excel - How to check if sheet is protected in IF In-built function?
[英]Pass verbose Excel's in-built function to a Cell using VBA
我在將內置Excel函數傳遞到單元格時遇到麻煩。 它不斷返回"Run-time error '1004': Application-defined or object-defined error".
基本上,我想做的是使用VBA創建平均/均值的動態演算。
With Sheets("TC7_DATA")
LastColumn = .Cells(4, Columns.Count).End(xlToLeft).Column
For i = 1 To Rows.Count
If (.Cells(i, 3).Value = "Average Value") Then
.Cells(i, LastColumn).Value = "=IF(AND(.Cells(i-3; LastColumn)=0; .Cells(i-2; LastColumn)=0; .Cells(i-1; LastColumn)=0);" - - - "; AVERAGE(.Cells(i-3; LastColumn), .Cells(i-3; LastColumn)))"
End If
Next i
End With
如果我在函數的前面插入不帶"="
的值,它將解釋為文本,並且不會出錯(當然,該函數實際上不起作用)。 我嘗試在不使用VBA的情況下在單元格的前面添加"="
,並且該功能正常運行。 如果我連接使用VBA
.Cells(i, LastColumn).Value = "=" & .Cells(i, LastColumn).Value
錯誤返回。
如何傳遞VERBOSE Excel內置函數:
("=IF(2>3; "True"; "False")")
使用VBA到單元格?
使用.Formula
代替。
其他幾點:
您不需要像其他語言一樣在If
語句中使用空格,除非您希望將語句分組在一起
您的For
循環未明確定義應為哪張紙
計算行數。 使用.Rows.Count
代替來指定工作表Sheets("TC7_DATA")
或聲明另一個工作表
您的For
循環還將遍歷工作表中的每一行
(可能是所有1,048,576個)。 這是非常冗長的。 ID
建議您只遍歷實際需要的內容。
您已經獲得了LastColumn
為什么不也獲得LastRow
使用類似LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
並在您的for循環中使用此值
With Sheets("TC7_DATA")
LastColumn = .Cells(4, Columns.Count).End(xlToLeft).Column
For i = 1 To Rows.Count
If .Cells(i, 3).Value = "Average Value" Then
.Cells(i, LastColumn).Formula = "=IF(AND(" & .Cells(i - 3, LastColumn) & "=0; " & .Cells(i - 2, LastColumn) & "=0; " & .Cells(i - 1, LastColumn) & "=0);"" - --""; AVERAGE(" & .Cells(i - 3, LastColumn) & ", " & .Cells(i - 3, LastColumn) & "))"
End If
Next i
End With
您必須寫入Formula屬性,而不是Value屬性。
例:
Sheets("CTC7_DATA").[A11].Formula ="=IF(2>3; "True"; "False")"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.