【问题标题】:How to sort Columns based on Headers using a list of all headers that are available?如何使用所有可用标题的列表根据标题对列进行排序?
【发布时间】:2019-10-05 06:31:17
【问题描述】:

我收到了几个不同的 Excel 电子表格,其中包含多达 30 个不同的列标题。我真的只需要每个电子表格中大约 8 或 10 列。我厌倦了左右滚动查找我需要的列。我想要一个宏,它会弹出一个包含所有可用标题的对话框。我想选择我想要的标题,然后从左到右剪切和粘贴它们,这样它们都彼此相邻。

我是 VBA 的新手,正在努力学习它,但这有点超出我的想象。帮助任何人??

我找到了每次以相同方式组织列的方法,但每个电子表格都有不同的列和顺序,因此我需要能够选择它们。

【问题讨论】:

    标签: excel vba columnsorting columnheader


    【解决方案1】:

    我建议使用带有列表框的用户表单,您可以在其中选择标题。 你可以试试下面的代码。

    要求: 用户表单 ListBox > Multiselect 属性应该是 = 1 按钮 > 将所选数据加载到新工作表中

    Dim mySH As Worksheet
    Dim oSH As Worksheet 'Output Worksheet
    
    
    Private Sub cmd_load_Click()
    
    Dim i As Integer
    Dim col_count As Integer
    col_count = 1
    Dim col_header As String
    Dim ns_srow As Integer
    ns_srow = 1
    
    'LOOP THRU ALL ITEMS IN LISTBOX AND GET ALL SELECTED
    For i = 0 To lst_header.ListCount - 1
        If lst_header.Selected(i) Then
            col_header = lst_header.List(i)
    
            'FIND THE COLUMN HEADER POSITION AND TRANSFER TO NEWSHEET THE DATA
            For a = 1 To mySH.Cells(1, Columns.Count).End(xlToLeft).Column
                If mySH.Cells(1, a).Value = col_header Then
                    For b = 1 To mySH.Cells(Rows.Count, a).End(xlUp).Row
                        oSH.Cells(ns_srow, col_count).Value = mySH.Cells(b, a).Value
                        ns_srow = ns_srow + 1
                    Next b
                    col_count = col_count + 1
                    ns_srow = 1
                    Exit For
                End If
            Next a
        End If
    Next i
    
    MsgBox "Data Completed"
    End
    
    
    End Sub
    
    Private Sub UserForm_Initialize()
    
    Set mySH = ThisWorkbook.Sheets("Data") 'name of your raw data worksheet
    Set oSH = ThisWorkbook.Sheets("Output") 'output worksheet
    'Assuming that column header is at row 1
    For a = 1 To mySH.Cells(1, Columns.Count).End(xlToLeft).Column
        lst_header.AddItem mySH.Cells(1, a).Value
    Next a
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 2016-10-26
      相关资源
      最近更新 更多