【问题标题】:VBA column doesn’t delete whenever header appears on sheet [duplicate]每当标题出现在工作表上时,VBA 列都不会删除 [重复]
【发布时间】:2018-12-21 02:04:53
【问题描述】:

我将一张表复制并粘贴到另一张表上,但数据量总是在变化。每当我粘贴时,会出现标有“总计”的工作表末尾的一列,但它会弄乱另一张工作表上的数据,所以我想将其删除。它从第二个代码中删除,但不是第一个。我需要帮助弄清楚为什么第一个不起作用。

 Set RidGrTotal = Range("B1:AH3000")
    isum.Sheets("pivot custom").Activate
    For Each cell In RidGrTotal
        If cell.Value = "Grand Total" Then cell.EntireColumn.ClearContents
    Next  

    Set RidGrandTotal = Range("B1:AH3000")
    isum.Sheets("Pivot to MW").Activate
    For Each cell In RidGrandTotal
        If cell.Value = "Grand Total" Then cell.EntireColumn.ClearContents
    Next

【问题讨论】:

  • 您可以在每行之前放置四个空格,而不是反引号。它看起来更好,更容易复制。
  • @wizzwizz4 更好的是,突出显示整个代码块并按键盘上的 Ctrl + K :)
  • Set RidGrTotal = Range("B1:AH3000") 此范围仅适用于运行时活动的任何工作表。您在该范围内循环两次,第二次这样做将没有效果,因为它只是重复它在第一次循环中所做的事情。您需要为每张纸重新分配它或使用一些替代方法来处理每张纸。

标签: excel vba


【解决方案1】:

适当地限定你的范围,你can avoid relying on Activate and all the problems that arise from implicit qualifications, etc.

Dim cell as Range
Dim addr = "B1:AH3000"


For Each cell In isum.Sheets("pivot custom").Range(addr)
    If cell.Value = "Grand Total" Then cell.EntireColumn.ClearContents
Next  

For Each cell In isum.Sheets("Pivot to MW").Range(addr)
    If cell.Value = "Grand Total" Then cell.EntireColumn.ClearContents
Next

【讨论】:

  • 啊,好吧,之前我不确定激活是如何发挥作用的,但这是有道理的,谢谢。
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 2020-03-29
  • 2018-03-15
  • 2017-06-28
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
相关资源
最近更新 更多