【问题标题】:VBA loop working but with Runtime Error at endVBA 循环正常工作,但最后出现运行时错误
【发布时间】:2019-04-26 15:28:48
【问题描述】:

我正在运行 For Each 循环,以根据位于每个相应工作表中的字符串的一部分重命名我的工作簿中的每个工作表。 'works' 下面的代码,意味着每个工作表都被重命名,但随后我得到 Runtime Error 1004 “Application-defined or Object-defined error”。

我尝试了几种修复方法,例如使用“ws”而不是“sht”,尝试使用单元格引用而不是“Range”,以及在我的 If 语句中设置 Else。

    For Each sht In ThisWorkbook.Worksheets
        If sht.Name <> "Control" Then
            sht.Name = Replace(sht.Range("A10"), "Using Restrictions of: Category Filter (Product) - ", "")
        End If
    Next

对于带有字符串“使用限制:类别过滤器(产品) - 旅行和运输”的工作表: 1-我希望工作表重命名为“Travel & Transport” 2-对于每个工作表(名为“控制”的工作表除外)相对于单元格 A10 中该工作表的字符串值进行重命名 3-为子结束没有错误。 实际:1 和 2 成功但没有 3

【问题讨论】:

    标签: excel vba loops


    【解决方案1】:

    执行完您的代码后,如果工作表的新名称最终为空白或超出其可以容纳的最大字符数,我将得到 Runtime Error 1004 “Application-defined or Object-defined error

    例如,如果在某些工作表中 A10 为空,则可能会发生这种情况。在这种情况下,新名称最终将变为空白。

    另一种可能发生这种情况的情况是,如果您搜索以替换的字符串与在 A10 中找到的字符串不同。例如,您正在搜索

    "Using Restrictions of: Category Filter (Product) - "
    

    但例如 A10 缺少空格字符:

    "Using Restrictions of: Category Filter (Product)- Travel & Transport"
    

    在这种情况下,新名称最终会等于超出最大字符数的 A10 值。

    另一种可能性是Control 工作表名称的拼写与If-statement 中的拼写不同。在这种情况下,所有工作表都将被重命名,如果 Control 中的 A10 为空,那么您将获得 Runtime Error 1004

    所以我的建议:

    1. 确保没有隐藏的工作表(右键单击工作表的选项卡并单击取消隐藏)
    2. 确保要从循环中排除的工作表是 拼写方式与您的If statement 完全相同
    3. 确保 "Control" 是唯一应从循环中排除的工作表
    4. 确保此"Using Restrictions of: Category Filter (Product) - " 在您创建的任何工作表中都没有拼写错误 想要重命名。
    5. 确保"Using Restrictions of: Category Filter (Product) - " 后面的字符不超过工作表名称可以容纳的最大字符数。

    【讨论】:

      【解决方案2】:

      为了测试,看看能不能做:

      dim sht as worksheet, z as string, arr as variant, x as long
      arr = Array("/", "\", "'", ",", "!", "@", "(", ")", "&", "-", "Using Restrictions of: Category Filter (Product) - ")
      For Each sht In ThisWorkbook.Worksheets
          If sht.Name <> "Control" Then 
              z = sht.cells(10,1).value
              For x = LBound(arr) To UBound(arr)
                  z = Replace(z, arr(x), "")
              Next x
              if len(z) > 0 then sht.Name = z
          End if
      Next
      

      我怀疑你的名字没有显示其他符号。

      当工作表名称要包含的字符串中有不必要的符号时,会出现以下错误:


      编辑1:

      在 z = 0 的情况下添加了一个 catch,因此 sht 名称不会更改

      【讨论】:

        猜你喜欢
        • 2018-08-12
        • 1970-01-01
        • 2022-10-09
        • 2021-02-10
        • 1970-01-01
        • 1970-01-01
        • 2021-11-07
        • 2013-08-09
        • 1970-01-01
        相关资源
        最近更新 更多