我有2个工作表,产品组和数据库:
我的工作表,产品组的布局如下:
A4
A5 {Button}
A6
A7
A8
用户可以在A4列中添加值。这意味着此列表可以扩展到A4-A8或A4至A100。
我创建了一个按钮,该按钮允许用户更新A。
中的值后运行宏此宏应将从A4到最后一行的值插入我的数据库表中的Cell T7中的数据验证。
这是我的代码:
Sub button()
Dim lastRow As Long
lastRow = ThisWorkbook.Worksheets("Product Groups").Range("A4" & Rows.Count).End(xlUp).Row
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Database")
Set ws2 = ThisWorkbook.Worksheets("Product Groups")
Set rng = ws.Range("T7")
Set range1 = ws2.Range("A1:A" & lastRow)
With rng.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws2.Name & "'!" & range1.Address
End With
End Sub
由于某种原因,我在此行上遇到了一个错误:
lastRow = ThisWorkbook.Worksheets("Product Groups").Range("A4" & Rows.Count).End(xlUp).Row
应用程序未定义或对象未定义错误。
请有人可以告诉我这出现在哪里吗?谢谢
解决方案已在注释
中给出我使用的答案再次显示了您的代码
的可能进行重构Option Explicit
Sub button()
Dim range1 As Range
With ThisWorkbook.Worksheets("Product Groups")
Set range1 = .Range("A1", .Cells(.Rows.count, 1).End(xlUp))
End With
With ThisWorkbook.Worksheets("Database").Range("T7").Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Formula1:="='Product Groups!" & range1.Address
End With
End Sub