VBA代码在macros中工作,但不在button上

当我在macros中逐行(F8)时,下面的代码工作正常。 但是,当我将它复制到表单“Cover”中的button上时,出现“Worksheet(”FES LIST“)时出现错误。范围(单元格(2,2),单元格(LastRow2,4))。 然后我在工作表“FES LIST”中创build另一个button,这是我执行“select”的工作表,代码再次开始工作。

有没有一种方法可以让我在表单“封面”中的button,但仍然select表中的“FES列表”范围? 非常感谢。

Private Sub CommandButton1_Click() 'This Code will remove any names defined in name manager Dim nm As Name On Error Resume Next For Each nm In ActiveWorkbook.Names nm.Delete Next On Error GoTo 0 'Find the last used row in a Column B and select range from B2 to D:LastRow Dim LastRow2 As Long With Worksheets("FES LIST") LastRow2 = .Cells(.Rows.Count, "B").End(xlUp).Row Sheets("FES LIST").Activate Worksheets("FES LIST").Range(Cells(2, 2), Cells(LastRow2, 4)).Select Worksheets("FES LIST").Range(Cells(2, 2), Cells(LastRow2, 4)).Name = "NameRange0" End With End Sub 

更改

 Sheets("FES LIST").Activate Worksheets("FES LIST").Range(Cells(2, 2), Cells(LastRow2, 4)).Select Worksheets("FES LIST").Range(Cells(2, 2), Cells(LastRow2, 4)).Name = "NameRange0" 

 With Worksheets("FES LIST") .Range(.Cells(2, 2), .Cells(LastRow2, 4)).Name = "NameRange0" End With 

哪些不使用。 .Activate/.Select ,也完全限定Cells对象。

尝试和testing

 Private Sub CommandButton1_Click() Dim nm As Name Dim LastRow2 As Long On Error Resume Next For Each nm In ActiveWorkbook.Names nm.Delete Next On Error GoTo 0 With Worksheets("FES LIST") LastRow2 = .Cells(.Rows.Count, "B").End(xlUp).Row .Range(.Cells(2, 2), .Cells(LastRow2, 4)).Name = "NameRange0" End With End Sub