避免在 Excel 中使用 ActiveCell 或 ActiveSheet

如果(出于任何原因)代码在错误的位置执行,使用 ActiveCellActiveSheet 可能是错误的来源。

ActiveCell.Value = "Hello" 
'will place "Hello" in the cell that is currently selected
Cells(1, 1).Value = "Hello" 
'will always place "Hello" in A1 of the currently selected sheet

ActiveSheet.Cells(1, 1).Value = "Hello" 
'will place "Hello" in A1 of the currently selected sheet
Sheets("MySheetName").Cells(1, 1).Value = "Hello" 
'will always place "Hello" in A1 of the sheet named "MySheetName"
  • 如果你的用户感到无聊并点击其他工作表或打开另一个工作簿,则使用 Active*会在长时间运行的宏中产生问题。
  • 如果你的代码打开或创建另一个工作簿,它可能会产生问题。
  • 如果你的代码使用 Sheets("MyOtherSheet").Select 并且在你开始阅读或写入之前忘记了你所使用的工作表,则可能会产生问题。