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

时间:2018-06-20 12:23:43

标签: excel vba excel-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到单元格?

2 个答案:

答案 0 :(得分:2)

改为使用.Formula

其他几点:

  • 您的If语句中不需要空格 语言,除非您希望将语句分组在一起

  • 您的For循环未明确定义应为哪张纸
    计算行数。使用.Rows.Count代替指定工作表 Sheets("TC7_DATA")或声明另一个工作表

  • 您的For循环还将遍历工作表中的每一行
    (可能是所有1,048,576个)。这是非常冗长的。我
    建议您只遍历实际需要的内容。
    您已经获得了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

答案 1 :(得分:0)

您必须写入Formula属性,而不是Value属性。

示例:

Sheets("CTC7_DATA").[A11].Formula ="=IF(2>3; "True"; "False")"