VBA:循环使用嵌套For Each工作表作为variables工作表

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

当我尝试在下面运行我的代码时,出现错误,我不确定是否将工作表作为Set语句中的variables进行操作。

似乎无法弄清楚/find一个解决scheme。

谢谢

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 

尝试这个:

 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方法,以确保find了某些东西

你可以试试这个

 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方法范围限制为使用的范围而不是整行。

唯一的警告是,所有search的工作表中的第一行不能是空的…

尝试第二个 – 每个这样的方式:

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