VBA 代码适用于宏,但不适用于按钮

标签 vba excel

当我在宏中逐行(F8)时,以下代码运行良好。但是,当我将其复制到工作表“Cover”中的按钮时,转到“Worksheets("FES LIST").Range(Cells(2, 2), Cells(LastRow2, 4)).Select”时出现错误。然后我在工作表“FES LIST”中创建了另一个按钮,这是我执行“选择”的工作表,代码再次开始工作。

有没有一种方法可以让我将按钮保留在工作表“封面”中,但仍然在工作表“FES LIST”中选择范围?非常感谢。

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 对象。

经过尝试和测试

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

关于VBA 代码适用于宏,但不适用于按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44342606/

相关文章:

excel - Worksheet.Columns 属性要求我提供 RowIndex?

javascript - 带有单选按钮的 html 表复制粘贴到 xls 中

excel - .range() 和 .cell() 相等的方法?

VBA - 查找重复并比较其中哪一个是最高的

c# - 使用 C# 构建 Excel 文件

VBA EXCEL在特定行上方添加空行[打开]

macos - VBA 在 Windows Excel 上运行,但不能在 Mac Excel 中运行

excel - Excel 的 ActiveX 组合框中存在错误?

excel - 根据多种条件将数据从 Access 导出到 Excel 工作簿/工作表

excel - 返回条件格式单元格内部颜色的函数