【问题标题】:VBA: looping through worksheets using nested For Each having worksheet as variableVBA:使用嵌套的 For Each 循环工作表,将工作表作为变量
【发布时间】:2016-07-25 12:36:06
【问题描述】:

vba 的新手在这里。我正在尝试通过将其嵌套在另一个 For Each 循环中,将一个简单的 For Each 循环(它使单元格

当我尝试在下面运行我的代码时,我收到一个错误,我不确定它是否与将工作表作为 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

【问题讨论】:

  • 错误在哪一行?
  • 运行时错误'91':对象变量或未设置块变量。错误似乎在第二个 For Each bit
  • 除了下面的建议之外,您还需要进行测试以确保找到“值”,您可能返回一个没有任何内容的范围对象。
  • 而不是Dim cell As Range 我认为应该是Dim cell As Cell
  • @PaulOgilvie Cell 因为范围是正确的。对于 excel vba。

标签: vba excel


【解决方案1】:

以这种方式尝试第二个 for-each:

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

【讨论】:

    【解决方案2】:

    试试这个:

    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 进行检查。
    【解决方案3】:

    你可以试试这个

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 2018-06-21
      相关资源
      最近更新 更多