运行sub时,正确的公式给出“运行时错误'1004':应用程序定义或对象定义”错误

时间:2016-06-06 12:29:58

标签: excel vba excel-vba excel-formula formula

我想在B列中粘贴公式,两者之间有延迟。公式应该只粘贴公式,如果单元格留给它(如果是B1,这是A1)不是空的,如下所示:

enter image description here

我有以下VBA粘贴公式,延迟时间为1秒。

    Option Explicit

Sub RetrieveDataDelay()
'paste formulas into cells, then calculate, then delay rinse repeat

    '=========================
    'Declare Variables
    '=========================
        Dim i As Long 'used to loop
        Dim rowCount As Long
        Dim LastRow As Long 'used to find the last row

    '=========================
    'Setup for Speed
    '=========================
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual

    '=========================
    'Define Variables
    '=========================
        LastRow = Worksheets(ActiveSheet.Name).Cells(Rows.Count, 1).End(xlUp).Row  'This will find the last used row in column A, change the number 1 to whatever column number you want
        rowCount = 1 ' set to how many rows you want to do at a time

    '=========================
    'Do Work
    '=========================
        For i = 1 To LastRow Step rowCount
            Range("B" & i, "B" & WorksheetFunction.Min(i + rowCount - 1, LastRow)).Formula = "'=IF(ISBLANK(A" & i & ");" & """" & """" & ";Dump(Volumes(A" & i & ";2528;1010;TRUE;" & "Volume" & ";TRUE)))" 'set the formula to whatever it needs to be
                Calculate
                    Application.Wait (Now + TimeValue("00:00:01")) 'this delays 1 second
        Next i

    '=========================
    'Setup for Speed - Reverse
    '=========================
        Application.ScreenUpdating = True
        Application.Calculation = xlCalculationAutomatic

End Sub

此部分发生错误

Range("B" & i, "B" & WorksheetFunction.Min(i + rowCount - 1, LastRow)).Formula = "=IF(ISBLANK(A" & i & ");" & """" & """" & ";Dump(Volumes(A" & i & ";2528;1010;TRUE;" & "Volume" & ";TRUE)))"

错误与公式有关,它不接受。这是与excel扩展一起使用的自定义公式。我知道这个公式有效,因为我在前面放了一个引号:

Range("B" & i, "B" & WorksheetFunction.Min(i + rowCount - 1, LastRow)).Formula = "'=IF(ISBLANK(A" & i & ");" & """" & """" & ";Dump(Volumes(A" & i & ";2528;1010;TRUE;" & "Volume" & ";TRUE)))"

因此它正式贴上了字面意思。如果我然后从公式中删除引号,则公式有效。所以问题仍然是为什么它不接受VBA中的这个特定公式。

使用Excel 2013。

1 个答案:

答案 0 :(得分:1)

Range.Formula需要始终采用en_us格式的公式表示法,与当前语言环境设置无关。这意味着使用英语和逗号作为公式参数之间的分隔符而不是分号。

所以

.Formula = "=IF(ISBLANK(A" & i & ")," & """" & """" & ",Dump(Volumes(A" & i & ",2528,1010,TRUE," & "Volume" & ",TRUE)))"

设置Range.Formula后,区域设置在工作表中仍然有效。因此,在工作表中,如果设置了分子,公式将以分号分隔。

顺便说一句:双引号的复杂字符串表示法不是必需的。

.Formula = "=IF(ISBLANK(A" & i & "),"""",Dump(Volumes(A" & i & ",2528,1010,TRUE," & "Volume" & ",TRUE)))"