拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 为每个列标题创建一个新作业表

为每个列标题创建一个新作业表

白鹭 - 2022-03-02 2052 0 0

对于每个列标题,获取每列中的资料并创建一个包含单行资料的新作业表

为了澄清并提供更多背景信息,我目前有以下格式的表格:

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)

希望这提供了足够的背景关系来解决问题。

uj5u.com热心网友回复:

创建标题作业表

  • 这只是一个基本的例子。表格(一行标题)必须是连续的(没有空的行或列)并且它必须从 cell 开始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
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *