我正在尝试使用以下代码
选择之前已过滤的工作表(数据库)的1列中的所有可见单元格
将验证应用于所有这些可见单元格,保留在单独的工作表中的1个动态列(SKU检查)。在行Set tbl_5 = Activesheet.......
,vba返回error 9, subscript out of range
。在到达此模块之前,数据库表已经过滤。
知道它的引用吗?数据库表是表数据,不确定是否会改变任何内容......
代码:
Sub VALIDATION_c()
Dim tbl_5 As ListObject
Dim rng As Range
Dim PH5Rng As Range
Dim Val5 As Range
Dim WS As Workbook
Sheets("Database").Select
Set tbl_5 = ActiveSheet.ListObjects("SKU Check").ListColumns(2).DataBodyRange.Select
Set rng = tbl_5.DataBodyRange.SpecialCells(xlCellTypeVisible)
Set Val5 = Sheets("SKU Check").Range("G1:G20")
Set WS = ThisWorkbook.Worksheets("SKU CHECK")
For Each tbl_5 In rng.Areas
With tbl_5.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & WS.Name & "'!" & Val5.Address
End With
Next
MsgBox ("DONE VALIDATION")
End Sub
答案 0 :(得分:0)
您的代码中存在以下几个问题:
就像@Ralph在评论中指出的那样,不可能有一个名为“SKU Check”的表
定义tbl_5:Dim tbl_5 As ListObject
您实际上是在分配.Select操作的结果
WS定义为Dim WS As Workbook
要修复代码,在工作表(“数据库”)中提供一个名为“SKUCheck”的表:
Option Explicit
Sub VALIDATION_c()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim tbl As ListObject
Dim col1 As Range
Dim col2 As Range
Set ws1 = Worksheets("Database")
Set ws2 = Worksheets("SKU Check")
Set tbl = ws1.ListObjects("SKUCheck")
Set col1 = tbl.DataBodyRange.Columns(2).SpecialCells(xlCellTypeVisible)
Set col2 = ws2.Range("G1:G20")
With col1.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws2.Name & "'!" & col2.Address
End With
MsgBox ("DONE VALIDATION")
End Sub