Excel宏将一对多关系转换为一对多

时间:2018-11-27 12:07:49

标签: excel vba excel-vba

我有两列-一列是“组名”,另一列是“用户”,看起来像这样:

Input

我需要将其转换为将所有组显示为列标题,并显示相应组下的所有用户,如下所示:

Output

该宏将在大量组上运行,而用户数量没有此限制。如果有100个组,则宏将创建100个列,并在各个组下列出用户。

2 个答案:

答案 0 :(得分:1)

  1. 确保源数据按GroupName排序。
  2. 遍历所有数据行。
  3. 每次GroupName更改时,都移至新列并写入标题
  4. 将用户写入当前的目标列

这里是一个例子:

Option Explicit

Public Sub ConvertData()
    Dim wsSrc As Worksheet
    Set wsSrc = ThisWorkbook.Worksheets("DataSource")

    Dim wsDest As Worksheet
    Set wsDest = ThisWorkbook.Worksheets("DataOutput")

    'sort data by GroupName
    With wsSrc.Sort
        .SortFields.Clear
        .SortFields.Add2 Key:=Range("A1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .SetRange Range("A:B")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With


    Dim LastRow As Long 'find last used row in column A
    LastRow = wsSrc.Cells(wsSrc.Rows.Count, "A").End(xlUp).Row

    Dim CurrentGroup As String

    Dim DestCol As Long, DestRow As Long 'counters for destination column and row
    DestCol = 0 'destination column

    Dim iRow As Long
    For iRow = 2 To LastRow 'loop through all data rows
        If wsSrc.Cells(iRow, 1).Value <> CurrentGroup Then 'if GroupName changed …
            CurrentGroup = wsSrc.Cells(iRow, 1).Value 'remember new group name
            DestCol = DestCol + 1 'move destination 1 column further
            DestRow = 1 'start at the top in this new column
            wsDest.Cells(DestRow, DestCol).Value = CurrentGroup 'write header (GroupName) of new group into the column
        End If

        'write user …
        DestRow = DestRow + 1 'move to the next free row
        wsDest.Cells(DestRow, DestCol).Value = wsSrc.Cells(iRow, 2).Value
    Next iRow
End Sub

答案 1 :(得分:0)

为此,答案数据包含在Sheet1中,并在Sheet2的组中分开。

尝试:

 Device.BeginInvokeOnMainThread(()=>{
 var result = conn.QueryAsync<RetailerGroupTable>("SELECT * FROM tblRetailerGroup WHERE RetailerCode=?", code).Result.FirstOrDefault();
provincePicker.SelectedItem = result;
                    });