繁体   English   中英

使用VBA将详细的Excel内置函数传递给单元格

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM