在所有活动工作表中应用相同的Excel-VBA代码

时间:2019-07-11 03:00:41

标签: excel vba

在为所有工作表应用以下代码时需要帮助。我已经尝试过在网上找到的代码ApplyToAllSheets(),但是我仍然是新手,我不知道如何使它工作。请帮忙。

Sub ApplyToAllSheets()

    Dim wks As Worksheet
    For Each wks In ThisWorkbook.Worksheets
        Third wks
    Next

End Sub

Sub Third(wks As Worksheet)
Dim Rng As Range
Dim cell As Range
Dim ContainWord As String
    With wks
        Set Rng = .Range(.Range("B1"), .Range("B" & .Rows.Count).End(xlUp))
    End With

'For deleting the remaining informations not necessary
  Set Rng = Range("B1:B1000")
  ContainWord = "-"
  For Each cell In Rng.Cells
    If cell.Find(ContainWord) Is Nothing Then cell.Clear
  Next cell
  Set Rng = Range("C1:C1000")
  ContainWord = "2019" 'change to current year
  For Each cell In Rng.Cells
    If cell.Find(ContainWord) Is Nothing Then cell.Clear
  Next cell
  Set Rng = Range("A1:A1000")
  ContainWord = "-"
  For Each cell In Rng.Cells
    If cell.Find(ContainWord) Is Nothing Then cell.Clear
  Next cell

'For deleting the blanks
On Error Resume Next
ActiveSheet.Range("B:B").SpecialCells(xlBlanks).EntireRow.Delete
    On Error GoTo 0

'For shifting the date to the left
Columns("C").Cut
Columns("A").Insert Shift:=xlToLeft
Columns("C").Cut
Columns("B").Insert

'For deleting the negative sign "-"
With Columns("B:B")
    .Replace What:="-", Replacement:=""
End With

End Sub

它应该成功将代码应用于所有工作表 我的结果是第一张纸始终被清除,而其他纸未触及。请帮助

1 个答案:

答案 0 :(得分:2)

您不合格-意味着Worksheet不合格-RangeColumns通话。

这很好-请注意Range的每个实例之前和Rows之前的时间段。

With wks
    Set Rng = .Range(.Range("B1"), .Range("B" & .Rows.Count).End(xlUp))
End With

这个,不是很多:

Set Rng = Range("B1:B1000") ' no worksheet specified, so it's the ActiveSheet, not wks.

或再次:

Columns("C").Cut

首先将End With一直移动到Sub的末尾,然后在Range和{{ 1}}。这样,他们将引用Columns,而不暗示wks

在使用时,请将ActiveSheet的实例更改为ActiveSheet。您想使用wks,而不是wks