列表对象与先前过滤的单元格

时间:2015-07-02 14:43:44

标签: excel vba excel-vba

我正在尝试使用以下代码

  1. 选择之前已过滤的工作表(数据库)的1列中的所有可见单元格

  2. 将验证应用于所有这些可见单元格,保留在单独的工作表中的1个动态列(SKU检查)。在行:设置tbl_5 =活动表....... vba返回错误9,下标超出范围。在到达此模块之前,数据库表已经过滤。

  3. 目前我收到错误,因为Set tbl_5值需要Object

    代码:

    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
    

2 个答案:

答案 0 :(得分:0)

与此问题中的答案相同:Error 9 on a DataBodyRange selection of a previously filtered sheet

您的代码中存在以下几个问题:

  1. 不可能有一个名为" SKU Check"

    的表
    • ListObjects名称不能包含空格
    • 这是导致您的"错误9:下标超出范围"
    • 的原因
  2. 定义tbl_5:Dim tbl_5 As ListObject

    • 您尝试将DataBodyRange分配给此ListObjects。由于类型名称暗示:
      • A" ListObject"是一个对象
      • A" DataBodyRange"是一个Range对象
      • 这会产生错误
  3. 您实际上是在分配.Select操作的结果

    • .Select返回包含True或False(操作结果)的Variant
  4. WS定义为Dim WS As Workbook

    • 您尝试为其分配一个Worksheet对象,它将生成另一个错误
  5. 要修复代码,在工作表("数据库")上提供代码,你就有了一个名为" 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
    

答案 1 :(得分:0)

请通过电子邮件发送 您的代码无效 子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("C8.-INSUMOS")
Set ws2 = Worksheets("C13.- PU")
Set tbl = ws1.ListObjects("TABLAINSUDINAMIC")

Set col1 = tbl.DataBodyRange.Columns(1).SpecialCells(xlCellTypeVisible)
Set col2 = ws2.Range("A:A")

With col1.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
         Formula1:="='" & ws2.Name & "'!" & col2.Address
End With

结束子