当我单步执行代码(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"")"
请注意,您也不应该激活
。相反,请使用适当的工作表来限定您的Range
、Cells
和Rows
调用。请注意下面的 Cells
、Rows
和 Range
之前的 .
:
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/