我有2个工作表,产品组和数据库:
我的表格,产品组的布局如下:
A4
A5 {Button}
A6
A7
A8
用户可以向列A4添加值。这意味着此列表可以扩展到A4-A8或A4到A100。
我创建了一个按钮,允许用户在更新A列中的值后运行宏。
此宏应将数据从A4到最后使用的行插入我的数据库表格中的单元格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
应用程序未定义或对象未定义错误。
有人可以告诉我哪里出了问题吗?感谢
答案 0 :(得分:0)
解决方案已在评论中提供
我使用的答案再次显示了您的代码
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