以下是可以实现您所需功能的VBA代码:

Sub SplitByColumnB()

    Dim lastRow As Long
    Dim currentRow As Long
    Dim currentName As String
    Dim newSheet As Worksheet
    
    '获取最后一行
    lastRow = Cells(Rows.Count, "B").End(xlUp).Row
    
    '循环B列中的每一行
    For currentRow = 2 To lastRow
        
        '获取当前名称
        currentName = Cells(currentRow, "B").Value
        
        '如果该名称的表页不存在,则新建一个表页
        If Not SheetExists(currentName) Then
            Set newSheet = Worksheets.Add(After:=Worksheets(Worksheets.Count))
            newSheet.Name = currentName
            '复制原表格的格式和标题
            Range("A1").EntireRow.Copy newSheet.Range("A1")
        Else
            Set newSheet = Worksheets(currentName)
        End If
        
        '将当前行复制到新表页中
        Range("A" & currentRow).EntireRow.Copy newSheet.Range("A" & newSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1)
        
    Next currentRow
    
    '删除原表格
    Application.DisplayAlerts = False
    ActiveSheet.Delete
    Application.DisplayAlerts = True
    
End Sub


Function SheetExists(sheetName As String) As Boolean
    Dim sheet As Worksheet
    On Error Resume Next
    Set sheet = Worksheets(sheetName)
    SheetExists = Not sheet Is Nothing
End Function

请将此代码复制粘贴到VBA编辑器中,并在您的Excel表格中运行该宏。它将根据B列中的值将表格拆分为不同的表页,并使用该值作为每个表页的名称。新建的表页将保留原表的格式和标题。

Excel VBA: 按B列值拆分表格并保留格式和标题

原文地址: https://www.cveoy.top/t/topic/ol5Z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录