【问题标题】:create a new worksheet for each column header为每个列标题创建一个新工作表
【发布时间】:2022-01-28 06:26:15
【问题描述】:

对于每个列标题,获取每列中的数据并创建一个新的工作表,其中包含单行中的数据

为了澄清和提供更多背景信息,我目前有一个格式如下的表格:

Header A | Header B | ...
--------------------------
Data A1  | Data B1  | ...
Data A2  | Data B2  | ...
...

我想要达到的目标如下:

For each column header
  Create a new worksheet with the header name
  Fill the worksheet with the following table:
    Data A1 | Data A2 | Data A3 | ... (tldr, for each header, get data and create a table where 
    the headers of the new table are the data relevant to the specific header)

希望这提供了足够的上下文来解决问题。

【问题讨论】:

  • 到目前为止你尝试过什么代码?你在哪里遇到了麻烦?请在您的问题中包括这一点。
  • 我不太确定从哪里开始,我对 VBA 很陌生,但是有其他语言的编码经验。

标签: excel vba


【解决方案1】:

创建页眉工作表

  • 这只是一个基本示例。表格(一行标题)必须是连续的(没有空行或空列),并且必须从单元格 A1 开始。
  • 调整常量部分中的值。
Option Explicit

Sub CreateHeaderWorksheets()
    
    Const sName As String = "Sheet1" ' Source Worksheet Name (has table)
    Const dfCellAddress As String = "A1" ' Destination Worksheets First Cell
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim sws As Worksheet: Set sws = wb.Worksheets("Sheet1")
    Dim srg As Range: Set srg = sws.Range("A1").CurrentRegion
    Dim rCount As Long: rCount = srg.Rows.Count - 1 ' minus headers
    
    Dim dws As Worksheet
    Dim scrg As Range
    Dim dName As String
    
    For Each scrg In srg.Columns
        dName = CStr(scrg.Cells(1).Value) ' header
        On Error Resume Next
        Set dws = wb.Worksheets(dName)
        On Error GoTo 0
        If Not dws Is Nothing Then ' delete if it exists
            Application.DisplayAlerts = False ' delete without confirmation
            dws.Delete
            Application.DisplayAlerts = True
        End If
        Set dws = wb.Worksheets.Add(After:=wb.Sheets(wb.Sheets.Count)) ' new
        dws.Name = dName
        dws.Range(dfCellAddress).Resize(, rCount).Value _
            = Application.Transpose(scrg.Resize(rCount).Offset(1).Value) ' write
        Set dws = Nothing ' reset because in loop
    Next scrg
    
    sws.Select
    
    MsgBox "Worksheets created.", vbInformation
    
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    相关资源
    最近更新 更多