-1

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

我在 Excel 中有这些数据:

excel数据

我想要做的是:如果监护人是“母亲”而不是监护人教育的列,它应该显示母亲的教育。如果监护人是“父亲”,则应显示父亲的教育程度,如下图所示。

例子

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

4

2 回答 2

2

为什么是vba?一个简单的公式代替监护人教育就可以了。

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

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

然后拖放到底部

于 2016-12-03T16:26:54.833 回答
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
于 2016-12-03T17:48:26.167 回答