VBA-计算同一列中2个值的次数

时间:2018-06-14 14:54:57

标签: excel vba scripting

我正在遍历工作簿,我想检查一个值是否出现在另一个工作表中,甚至一次,它还不在scrap2的列A中,然后将其附加到scrap2的A列。否则,如果它已经在scrap2的A列中,那么转到下一次迭代。我想要像Python中的pass语句。我得到的当前结果是相同值的多个副本,而不是每个唯一值。

Sub Main()

    Dim ws As Worksheets 
    Dim starting_ws As Worksheet
    Set starting_ws = ActiveSheet 
    ws_num = ThisWorkbook.Worksheets.Count - 2

    For I = 1 To ws_num
        ind = 9
        name_ind = 7
        ThisWorkbook.Worksheets(I).Activate
        Do While ind <= 39
    If IsError(Application.Match(Worksheets(I).Range("A" & ind).Value, Worksheets("scrap2").Range("A7,A30").Value, False)) Then
                 Worksheets("scrap2").Range("A" & name_ind).Value = Worksheets(I).Range("A" & ind).Value
            Else
                Worksheets("scrap2").Range("A" & name_ind).Value = Worksheets("scrap2").Range("A" & name_ind).Value


            End If
            ind = ind + 1
            name_ind = name_ind + 1
        Loop


    Next
End Sub

1 个答案:

答案 0 :(得分:0)

试试这个:

Sub Main()

Dim ws As Worksheets 
Dim starting_ws As Worksheet
Set starting_ws = ActiveSheet 
ws_num = ThisWorkbook.Worksheets.Count - 2
Dim SourceCell As Range, DestinationRange As Range


For I = 1 To ws_num
    ind = 9
    name_ind = 7
    ThisWorkbook.Worksheets(I).Activate
    Do While ind <= 39
        'Set these to variables for readability
        Set SourceCell = Worksheets(I).Range("A" & ind)
        Set DestinationRange = Worksheets("scrap2").Range("A7:A30") ' NOT ("A7,A30")

        If IsError(Application.Match(SourceCell.Value, DestinationRange, False)) Then
             Worksheets("scrap2").Range("A" & name_ind).Value = SourceCell.Value
             name_ind = name_ind + 1 'Put this here so it doesn't leave blank lines
        Else
             'You don't really need this section. You can just omit the "Else" line.
        End If

        ind = ind + 1
    Loop
Next
End Sub