Excel VBA将数据与列进行比较

时间:2016-12-03 16:15:18

标签: excel vba excel-vba vbe

我是excel VBA代码的新手。如果有人可以帮助我,我需要它来完成任务。

我在Excel中有这些数据:

excel data

我想要做的是:如果监护人是“母亲”,而不是监护人教育专栏,那么它应该显示母亲的教育。如果监护人是“父亲”,那么它应该显示父亲的教育,如下图所示。

example

我需要使用VBA代码为大型数据集执行此操作。

2 个答案:

答案 0 :(得分:2)

为何选择vba?一个简单的公式来代替监护人教育。

假设数据位于第二行,请使用此公式。

=IF(C2="mother",A2,IF(C2="father",B2,"");

然后拖放到底部

答案 1 :(得分:0)

你可以尝试这个(评论过的)代码:

Option Explicit

Sub main()        
    With Worksheets("Edu") '<--| change "Edu" to your actual worksheet with data name
        With .Range("A1", .Cells(.Rows.count, "C").End(xlUp)) '<--| reference its columns A to C range from row 1 down to column A last not empty cell one
            .Resize(, 1).Offset(, 4).Value = Application.Transpose(GetOrdinals(.Rows.count)) '<--| write initial order index in column "E" (it'll be deleted by the end of the macro)
            .Resize(, .Columns.count + 2).Sort key1:=.Columns(3), Header:=xlYes '<--| order columns A to E by column C ("guardian")
            SetGuardian .Columns(3), "mother", 1, -2 '<--| fill column "D" (1 offset column from column "C) with column "A" (2 column offset from column "C") values
            SetGuardian .Columns(3), "father", 1, -1 '<--| fill column "D" (1 offset column from column "C) with column "B" (2 column offset from column "C") values
            .Parent.AutoFilterMode = False '<--| remove autofilter mode and show all rows back
            .Resize(, .Columns.count + 2).Sort key1:=.Columns(5), Header:=xlYes '<--| sort columns A to E by initial order index column to get them back to their original position
            .Resize(, 1).Offset(, 4).ClearContents '<--| clear initial order index column
        End With
    End With
End Sub

Sub SetGuardian(data As Range, guardian As String, targetColOffset As Long, sourceColOffset As Long)
    With data
        .AutoFilter field:=1, Criteria1:=guardian '<--| filter referenced cells with passed 'guardian'
        If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then
            With .Resize(.Rows.count - 1).Offset(1).SpecialCells(xlCellTypeVisible)
                .Offset(, targetColOffset).Value = .Offset(, sourceColOffset).Value
            End With
        End If
    End With
End Sub

Function GetOrdinals(max As Long) As Variant
    Dim i As Long
    ReDim arr(1 To max) As Long

    For i = 1 To max
        arr(i) = i
    Next i
    GetOrdinals = arr
End Function