百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

VBA,拆分Excel工作表 如何用vba拆分excel表到新的工作簿

wptr33 2024-12-16 16:30 34 浏览

又找到一个小工具:

根据设置的参数,自动拆分工作表为多个工作簿文档。


主要代码,如:

Sub StartToSplit(strSavedPath As String, ByVal arrNewBookSheets As Variant)

    Dim i As Integer
    
    Dim wbNew As Workbook
    Dim strwbNewName As String
    Dim strwbNewFullName As String
        
    Dim strActiveBookBaseName As String
    strActiveBookBaseName = GetWorkbookBaseName()
    
    Dim strNewSheets As String
    strNewSheets = GetAllCheckedItemsName(Me.ListView1)
    
    intMaxLen = Len(CStr(UBound(arrNewBookSheets)))
    
    Application.ScreenUpdating = False
    
    Dim strSplitFieldValue As String
    
    For i = LBound(arrNewBookSheets) To UBound(arrNewBookSheets)
    
        strSplitFieldValue = arrNewBookSheets(i)
        
        '遇到空白单元格,直接跳出!
        If Len(Trim(strSplitFieldValue)) = 0 Then
            Exit Sub
        End If
 
        
        If Me.规则0.Value = True Then
            strwbNewName = FormatNumberWithLeadingZeros(i + 1, intMaxLen) & ":" & strSplitFieldValue & ".xlsx"
        End If
        
        If Me.规则1.Value = True Then
            strwbNewName = strActiveBookBaseName & "(" & strSplitFieldValue & ")" & ".xlsx"
        End If
        
        If Me.规则2.Value = True Then
            If Trim(Me.TextBox自定义名称.Text) = "" Then
                strwbNewName = strSplitFieldValue & ".xlsx"
            Else
                strwbNewName = CleanFileName(Trim(Me.TextBox自定义名称.Text)) & "(" & strSplitFieldValue & ")" & ".xlsx"
            End If
        End If
        
        '创建的工作簿,有副本?
        
        Set wbNew = CreateWorkbookWithSheets(strNewSheets)
        
        Dim strLines  As String
        strLines = GetAllCheckedItemsAsString(Me.ListView1)
        

        Call CopyLine(activeSourceWorkbook, strLines, strSplitFieldValue, wbNew)
        
        Dim objSheetAdded As Worksheet
        
        
        For Each objSheetAdded In wbNew.Worksheets
            
            objSheetAdded.Columns.AutoFit
        
        Next
        
        
        wbNew.SaveAs (strSavedPath + strwbNewName)
        Call wbNew.Close(True, strSavedPath + strwbNewName)
        Set wbNew = Nothing
  
    Next i
    
    Application.ScreenUpdating = True

End Sub

Sub CopyLine(ByVal wbSource As Workbook, ByVal strLines As String, ByVal strSplitFieldValue As String, ByVal wbDestination As Workbook)

    Dim lineArray() As String
    Dim detailArray() As String
    Dim strline As String
    Dim strName As String
    Dim intRow As Integer
    Dim intColumn As Integer
    Dim wsSource As Worksheet
    Dim wsDest As Worksheet
    Dim lastRow As Long
    Dim copyRange As Range
    Dim cell As Range
    
    lineArray = Split(strLines, "|")
    
    For i = LBound(lineArray) To UBound(lineArray)
        strline = lineArray(i)
        detailArray = Split(strline, ";")
        
        If UBound(detailArray) >= 2 Then
        
            strName = detailArray(0)
            intRow = CInt(detailArray(1))
            intColumn = CInt(detailArray(2))
            
            Set wsSource = wbSource.Sheets(strName)
            Set wsDest = wbDestination.Sheets(strName)
            
            
            Set copyRange = wsSource.Range("A1").Resize(intRow - 1, wsSource.Columns.Count)
            copyRange.Copy
            wsDest.Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
            Application.CutCopyMode = False
            

            lastRow = wsDest.Cells(wsDest.Rows.Count, intColumn).End(xlUp).Row + 1
            Dim hasFormula As Boolean
 
    
    
            For Each cell In wsSource.Range(wsSource.Cells(intRow, intColumn), wsSource.Cells(wsSource.Rows.Count, intColumn))
                If cell.Value = strSplitFieldValue Then
                    hasFormula = RowHasFormula(GetUsedCellsInRow2(cell.EntireRow))
                    
                    cell.EntireRow.Copy
                    wsDest.Cells(lastRow, 1).PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
            
                    If hasFormula Then
                        wsDest.Cells(lastRow, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
                    End If
            
                    wsSource.Rows(cell.Row).Copy
                    wsDest.Rows(lastRow).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
            
                    lastRow = lastRow + 1
                End If
            Next cell
            Application.GoTo Reference:=wsDest.Cells(1, 1)
            Application.CutCopyMode = False


            
        End If
    Next i
End Sub



Function GetColumnValues(strSheetName As String, intStartRow As Integer, intSplitColumn As Integer) As Variant

    Dim ws As Worksheet
    Dim lastRow As Long
    Dim values() As Variant
    Dim i As Long
 
    On Error Resume Next
    Set ws = activeSourceWorkbook.Worksheets(strSheetName)
    
    If ws Is Nothing Then
        GetColumnValues = Null
        Exit Function
    End If
    
    lastRow = ws.Cells(ws.Rows.Count, intSplitColumn).End(xlUp).Row
    
    If intStartRow > lastRow Then
        GetColumnValues = Null
        Exit Function
    End If
 
    ReDim values(1 To lastRow - intStartRow + 1)
    For i = intStartRow To lastRow
        values(i - intStartRow + 1) = ws.Cells(i, intSplitColumn).Value
    Next i
    GetColumnValues = values
    
End Function



Function GetFirstCheckedListViewItemValue(ByVal ListViewCtrl As ListView) As String
    Dim i As Integer
    For i = 1 To ListViewCtrl.ListItems.Count
        If ListViewCtrl.ListItems(i).Checked Then
            Dim checkedItem As ListItem
            Set checkedItem = ListViewCtrl.ListItems(i)
            GetFirstCheckedListViewItemValue = checkedItem.Text & ";" & checkedItem.ListSubItems(1).Text & ";" & checkedItem.ListSubItems(2).Text
            Exit Function
        End If
    Next i
    GetFirstCheckedListViewItemValue = ""
End Function


Function GetAllCheckedItemsName(ListViewCtrl As ListView) As String

    Dim i As Integer
    Dim result As String
    result = ""

    For i = 1 To ListViewCtrl.ListItems.Count
        If ListViewCtrl.ListItems(i).Checked Then
            result = result & ListViewCtrl.ListItems(i).Text & ";"
        End If
    Next i

    If Len(result) > 0 Then
        result = Left(result, Len(result) - 1)
    End If

    GetAllCheckedItemsName = result
    
End Function

相关推荐

Linux文件系统操作常用命令(linux文件内容操作命令)

在Linux系统中,有一些常用的文件系统操作命令,以下是这些命令的介绍和作用:#切换目录,其中./代表当前目录,../代表上一级目录cd#查看当前目录里的文件和文件夹ls#...

别小看tail 命令,它难倒了技术总监

我把自己以往的文章汇总成为了Github,欢迎各位大佬star...

lnav:基于 Linux 的高级控制台日志文件查看器

lnav是一款开源的控制台日志文件查看器,专为Linux和Unix-like系统设计。它通过自动检测日志文件的格式,提取时间戳、日志级别等关键信息,并将多个日志文件的内容按时间顺序合并显示,...

声明式与命令式代码(声明模式和命令模式)

编程范式中的术语和差异信不信由你,你可能已经以开发人员的身份使用了多种编程范例。因为没有什么比用编程理论招待朋友更有趣的了,所以这篇文章可以帮助您认识代码中的流行范例。命令式编程命令式编程是我们从As...

linux中的常用命令(linux常用命令和作用)

linux中的常用命令linux中的命令统称shell命令shell是一个命令行解释器,将用户命令解析为操作系统所能理解的指令,实现用户与操作系统的交互shell终端:我们平时输入命令,执行程序的那个...

提高工作效率的--Linux常用命令,能够决解95%以上的问题

点击上方关注,第一时间接受干货转发,点赞,收藏,不如一次关注评论区第一条注意查看回复:Linux命令获取linux常用命令大全pdf+Linux命令行大全pdf...

如何限制他人操作自己的电脑?(如何控制别人的电脑不让发现)

这段时间,小猪罗志祥正处于风口浪尖,具体是为啥?还不知道的小伙伴赶紧去补一下最近的娱乐圈八卦~简单来说,就是我们的小罗同事,以自己超强的体力,以及超强的时间管理能力,重新定义了「多人运动」的含义,重新...

最通俗易懂的命令模式讲解(命令模式百科)

我们先不讲什么是命令模式,先通过一个场景来引出命令模式,看看命令模式能解决什么样的问题。现在有一个渣男张三,他有还几个女朋友,你现在是不是还是单身狗,你就说你气不气?然后他需要每天分别叫几个女朋友起床...

互联网大厂后端必看!Spring Boot 中Runtime执行与停止命令?

你是否曾在使用SpringBoot开发项目时,遇到需要执行系统命令的场景?比如调用脚本进行文件处理,又或是启动外部程序?很多后端开发人员会使用Processexec=Runtime.get...

Linux 常用命令(linux常用的20个命令面试)

日志排查类操作命令...

Java字节码指令:if_icmpgt(0xA3)(java字节码使用的汇编语言)

if_icmpgt是Java字节码中的一条条件跳转指令,其全称是"IfIntegerCompareGreaterThan"。它用于比较两个整数值的大小。如果栈顶的第一个...

外贸干货|如何增加领英的曝光量和询盘

#跨境电商#...

golang执行linux命令(golang调用shell脚本)

需求需要通过openssl生成rsa秘钥,然后保存该秘钥。代码实例packagemainimport("io/ioutil""bytes"&...

LINUX磁盘挂载(linux磁盘挂载到windows)

1、使用root用户查看磁盘挂载情况:fdisk-l2、使用df查看当前磁盘挂载情况,根据和fdisk-l的结果进行对比,查看还有那些磁盘未使用3、挂载:mount磁盘挂载路径...

Linux命令学习——nl命令(linux ln命令的使用)

nl命令主要功能为每一个文件添加行号,每一个输入的文件添加行号后发送到标准输出。当没有文件或文件为-时,读取标准输入...