Warm tip: This article is reproduced from serverfault.com, please click

excel-VBA遍历工作表以删除重复项

(excel - VBA looping through sheets removing duplicates)

发布于 2020-11-28 12:42:06

我已经看到了类似的事情,但是我的代码似乎可以正常运行,我只想检查是否有改进或可能的错误以及意想不到的后果。

我收到的电子表格最终得到了重复的信息。有很多电子表格,有些电子表格每个文件中包含100张纸。显然,不想使用删除重复的信息来手动浏览每张纸。经过四处搜寻,我认为我有一个解决方案,希望你对此有意见。我有JS背景,这是我第一次使用vba。

Sub RemoveDuplicates()

'RemoveDuplicates宏'选择所有值,然后删除重复项'

 ' Declare Current as a worksheet object variable.
     Dim Current As Worksheet
     Dim starting_ws As Worksheet
     Set starting_ws = ActiveSheet 'remember which worksheet is active in the beginning

     ' Loop through all of the worksheets in the active workbook.
     For Each Current In Worksheets
        Current.Activate
        
        LastRow = Cells(Rows.Count, "A").End(xlUp).Row
        ActiveSheet.Range("A1" & LastRow).RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), Header:=xlYes
  
     Next
     
starting_ws.Activate 'activate the worksheet that was originally active

结束子

我只在每张纸上寻找重复项,而不是在工作表中寻找重复项。列数也将保持不变。非常感谢你的提前帮助。抱歉,这是基本的VB。

Questioner
Chris MacDonald
Viewed
11
VBasic2008 2020-11-28 23:01:11

删除重复项(多列和工作表)

  • 使用Option Explicit
  • ActiveSheet.Range("A1" & LastRow)肯定是错误的。想一想。
  • 你有资格RangeCellsRowsColumns例如Current.CellsCurrent.Rows.Count...
  • 你不必激活CurrentCurrentActiveSheet你的情况(因为你已激活它),因此无需使用ActiveSheet
  • 不要让Excel我们定义范围:你要定义它。

有问题的代码

Option Explicit

Sub removeDupes()
     
     ' Here's a question:
     '     Why can't I use 'Cols' instead of the array written explicitly?
     Dim Cols As Variant
     Cols = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
     
     Const FirstAddress As String = "A1"
     Dim wb As Workbook
     Set wb = ActiveWorkbook
     
     Dim ws As Worksheet
     Dim LastCell As Range
     
     For Each ws In wb.Worksheets
         Set LastCell = ws.Cells(ws.Rows.Count, "A").End(xlUp).Offset(, 10)
         ws.Range(FirstAddress, LastCell).RemoveDuplicates _
             Columns:=Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), Header:=xlYes
         ' This doesn't work.
         'ws.Range(FirstAddress, LastCell).RemoveDuplicates _
             Columns:=Cols, Header:=xlYes
     Next

End Sub