gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:30:02 27 4
gpt4 key购买 nike

当我在宏中逐行(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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com