我怎样才能确保我的代码一直正常运行
How can I make sure that my code runs properly all the time
当我逐步执行代码 (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
不需要Select
或使用ActiveCell
或AutoFill
。替换:
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"")"
请注意,您也不应该 Activate
ing。相反,限定 您的 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
当我逐步执行代码 (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
不需要Select
或使用ActiveCell
或AutoFill
。替换:
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"")"
请注意,您也不应该 Activate
ing。相反,限定 您的 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