VBA只能在某个工作表上运行

下面的代码将在macros运行时在第2列上方插入一个新行。 但是,如果我单击一个不同的工作表并运行该macros,它将插入一个新的行,而不是像我指定的Sheet 1 。 有没有一种方法可以让我运行macros时,只会在特定的表格上执行这些操作,而不pipe我在哪张表上?

With Worksheets("Sheet 1") Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove End With 

在“行”之前放一个点

您的参考“行”使用任何活动行(相当于ActiveSheet.Rows),但点将使用“With”块。

 With Worksheets("Sheet 1") .Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove End With 

没有点,With块甚至没有考虑,代码相当于:

  Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove 

爆炸操作员(!)也是如此。

参考:

  • 有声明的VBA

对于单行代码,我不打扰With语句:

 Worksheets("Sheet 1").Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove 

添加'。' 在行中…

 With Worksheets("Sheet 1") .Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove End With