首页 > 解决方案 > 首次运行后 VBA 代码中断 - 错误 91

问题描述

我正在尝试通过使用代码插入/复制/粘贴值和公式来半自动化文件。当我运行此代码一次时,它工作正常。尝试在任何后续时间运行代码都会导致“运行时错误 '91'”。调试错误突出显示了我尝试使用短语“na.Row”来调用代码中前面标识的行号的代码。

注意:我对 VBA 非常陌生,之前没有编码背景;我相信它可以更干净简洁。

Sub AdvtoStd_Click()

'Names the Worksheets

    Dim ws As Worksheet
    Set ws = Worksheets("Org")

    Dim ar As Worksheet
    Set ar = Worksheets("Adv. Retrieve")

    Dim sr As Worksheet
    Set sr = Worksheets("Std. Retrieve")


'Finds the cell with 'No_Account' and names it id

    Dim na As Range
    Set na = ws.Range("A:A").Find("No_Account", LookIn:=xlValues)

    Dim Aacts As Range
    Set Aacts = ar.Range("A:A").Find("Accounts", LookIn:=xlValues, LookAt:=xlWhole)


'Clears the old numbers on the Retail worksheet

    Worksheets("Retail").Activate
    Range("A4:E2000").ClearContents

'Copies the accounts from the Org to Retail worksheet

    ws.Range("A4:A2000").Copy
    Sheets("Retail").Range("A4:A2000").PasteSpecial xlPasteValues

'Inserts the VLookup into cells B4 and C4 + Inserts the Variance calculation in cell E4
'Copies the VLookup and Variance calculation down to 'No_Account'

    Sheets("Retail").Range("B4").Value = "=VLOOKUP(A4,'Adv. Retrieve'!A:I,3,FALSE)"
    Sheets("Retail").Range("C4").Value = "=VLOOKUP(A4,'Std. Retrieve'!A:I,3,FALSE)"
    Sheets("Retail").Range("E4").Value = "=C4-B4"
    Sheets("Retail").Range("B4:E4").Copy
    Sheets("Retail").Range("B5", Sheets("Retail").Range("E" & na.Row)).PasteSpecial xlPasteFormulas

'Calculates the TOTALs

    Sheets("Retail").Range("B" & na.Row + 2).Value = "=SUM(OFFSET(B1,,,ROW()-1,1))"
    Sheets("Retail").Range("C" & na.Row + 2).Value = "=SUM(OFFSET(C1,,,ROW()-1,1))"

'Copies the Hyperion values

    ar.Range("B" & Aacts.Row).Copy
    Sheets("Retail").Range("B" & na.Row + 3).PasteSpecial xlPasteValues

该错误发生在我试图将列中的公式粘贴B:E到 Account Names 以 column 结尾的行号的代码部分中A

就像我之前提到的,当我打开文件并运行一次时,代码完全按照预期工作,但是任何二次运行代码的尝试都会产生错误“91”。

标签: excelvba

解决方案


推荐阅读