excel - 如何确保我的代码始终正常运行

标签 excel vba

当我单步执行代码(F8)时,这段代码可以顺利运行,但是当我使用 F5 运行它或调用它从按钮运行时,它没有执行它应该执行的操作。它只在第一个单元格 (Q2) 中进行查找,并将其余部分留空 - 就像它跳过将公式运行到最后一行一样。

如何改进我的代码以确保它始终按预期运行?

Sub LookupFilename()
' Looks up the filename to be set according to Team Name

Application.ScreenUpdating = False

LastRow = Cells(Rows.Count, "A").End(xlUp).Row

    Range("Q2").Select
    ActiveCell.FormulaR1C1 = _
        "=IFERROR(VLOOKUP(RC[-3],Controller!C9:C12,4,FALSE),""Other"")"
    Range("Q2").AutoFill Destination:=Range("Q2:Q" & LastRow)

Application.ScreenUpdating = True

MsgBox "Successful data collection.", vbInformation, "Success"

End Sub

最佳答案

无需选择或使用ActiveCell自动填充。替换:

Range("Q2").Select
ActiveCell.FormulaR1C1 = _
    "=IFERROR(VLOOKUP(RC[-3],Controller!C9:C12,4,FALSE),""Other"")"
Range("Q2").AutoFill Destination:=Range("Q2:Q" & LastRow)

与:

Range("Q2:Q" & LastRow).FormulaR1C1 = _
    "=IFERROR(VLOOKUP(RC[-3],Controller!C9:C12,4,FALSE),""Other"")"

请注意,您也不应该激活。相反,请使用适当的工作表来限定您的RangeCellsRows 调用。请注意下面的 CellsRowsRange 之前的 .:

Dim Data As Worksheet
Set Data = ThisWorkbook.Worksheets("Data")

With Data
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    .Range("Q2:Q" & LastRow).FormulaR1C1 = _
        "=IFERROR(VLOOKUP(RC[-3],Controller!C9:C12,4,FALSE),""Other"")"
End With

关于excel - 如何确保我的代码始终正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71959877/

相关文章:

node.js - 如何从 Node.js 程序运行 Excel VBA?

Excel公式计算基于其他单元格的值

vba - 加载的 XML 文件会被缓存,不会更新

vba - 有条件地运行 VBA 代码

sql - 使用 SSIS 清除 Excel 中的数据

c# - 尝试使用 c# 按两列对 excel 范围进行排序

excel - 当 Excel 单元格区域中的数据更新时提示消息框

excel - VBA : Set Range from Cell Function

excel - 右键单击 withevents 适用于源 .xlsm 但不适用于 .xlam 插件

arrays - 将一整行数据放入二维数组