VBA:使用嵌套的For Each循环遍历工作表将工作表作为变量

时间:2016-04-05 14:01:01

标签: excel vba excel-vba

新手在vba这里。我试图通过将其嵌套在另一个For Each循环中,将一个简单的For Each循环(使单元格< 0无效)应用于工作簿中的所有工作表。

当我尝试运行下面的代码时,我得到一个错误,我不确定它是否与将工作表作为Set语句中的变量有关。

似乎无法弄明白/找到解决方案。

谢谢

Sub deleteNegativeValue()

Application.DisplayAlerts = False
Dim lastRow As Long
Dim ws As Worksheet
Dim cell As Range
Dim res As Range

For Each ws In Workbooks(1).Worksheets

Set res = ws.Range("1:1").Find("Value", lookat:=xlPart)
lastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

For Each cell In Range(ws.Cells(1, res.Column), ws.Cells(lastRow, res.Column))
If cell < 0 Then cell = ""
Next

Next

End Sub

3 个答案:

答案 0 :(得分:1)

试试这个:

Sub deleteNegativeValue()

Dim lastRow As Long
Dim ws As Worksheet
Dim cell As Range
Dim res As Range

For Each ws In ThisWorkbook.Worksheets

    Set res = ws.Range("1:1").Find("Value", lookat:=xlPart)
    lastRow = ws.Range("A" & Rows.Count).End(xlUp).row
    If Not res Is Nothing Then
        For Each cell In ws.Range(ws.Cells(1, res.Column), ws.Cells(lastRow, res.Column))
            If cell < 0 Then cell = ""
        Next
    Else
        MsgBox "No Value found on Sheet " & ws.Name
    End If

Next

End Sub

需要检查Find方法,以确保找到了某些内容

答案 1 :(得分:1)

你可以试试这个

Option Explicit

Sub deleteNegativeValue()

Dim ws As Worksheet
Dim res As Range

For Each ws In ThisWorkbook.Worksheets
    Set res = Intersect(ws.Rows(1), ws.UsedRange).Find("value", LookAt:=xlPart)
    If Not res Is Nothing Then
        ws.Columns(res.Column).SpecialCells(xlCellTypeConstants, xlNumbers).Replace What:="-*", Replacement:="", SearchOrder:=xlByColumns, MatchCase:=False, LookAt:=xlWhole
    Else
        MsgBox "No Value found on Sheet " & ws.Name
    End If
Next

End Sub

应该运行得更快,因为它不会遍历每列的每个单元格,并将Find方法范围限制为使用的范围而不是整行。

唯一的警告是,所有在工作表中搜索到的第一行都不能为空...

答案 2 :(得分:0)

以这种方式尝试第二种方式:

ws.Range(ws.Cells(1, res.Column), ws.Cells(lastRow, res.Column))