VBA:定义范围内的变量而不是单元格名称

时间:2014-07-16 23:14:28

标签: excel vba excel-vba cells worksheet

我有一个名为"选择名称"这是随机放在同一工作簿的很多工作表中。请问我想知道如何在工作簿的所有工作表中查找该单元格值。我尝试循环遍历所有工作表和第一行的所有单元格,查找该字符串值,但我似乎无法找到解决方案,这就是我所做的:

For Each ws In ActiveWorkbook.Worksheets 
    col_num = ws.Range("A1").End(xlToRight).Column 
       For Cel1 = 1 To clom_num 
         If ws.Cells(1, Cel1).Value = "Cell Name" Then 
         col_name = ws.Cells(2, Cel1).Name 
         End If 
       Next 
         With ws.Range("col_name:col_name").Validation   ' Here when i put ("L:L") it works, but that value can be in any cell
           .Delete 
           .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ 
    xlBetween, Formula1:=Liste 
           .IgnoreBlank = True 
           .InCellDropdown = True 
         End With 

哦,我确实收到了这个错误(使用ws.Range(" col_name:col_name")。验证)"对象_worksheet的方法范围失败"

请帮助

1 个答案:

答案 0 :(得分:1)

使用Range.Find方法代替循环:

    Dim ws As Worksheet
    Dim rngFound As Range

    For Each ws In ActiveWorkbook.Sheets
        Set rngFound = ws.Rows(1).Find("Cell Name", , xlValues, xlWhole)
        If Not rngFound Is Nothing Then
            With ws.Columns(rngFound.Column).Validation
                .Delete
                .Add xlValidateList, xlValidAlertStop, xlBetween, Liste
                .IgnoreBlank = True
                .InCellDropdown = True
            End With
        End If
    Next ws