[Powershell / VBA] To split Excel sheets to individual workbooks.

1 week ago I still in a wonderful city for business trip, that‘s a great trip I been through so far. So great for the city and my colleagues, I still remember it from time to time~

Ok, today I inadvertently saw some posts regarding to split excel sheets to workbooks, I thought someday I will face the same situation in future from others. So, I gave it a shot to achieve in powershell and VBA, as a solution for my future customers.

Powershell

First of all, we have a xlsx file contains several sheets, our goal here is to save each sheet into a workbook.

To access excel in script, the most way I used is COM object. So let‘s create one, of course set alert as false will release us from many excel alerts.

$Excel = New-Object -ComObject Excel.Application
$Excel.DisplayAlerts = $false

this basicly means I opened a excel.exe, if I want to see it, there is a property $Excel.Visible, set it to true you will see.

then, I use below code to open target excel file, beaware the "Workbooks.Open()" method only accept full path.

$WorkBook = $Excel.Workbooks.Open("$PWD\all.xlsx")

Now $WorkBook.Sheets contains all sheets, all we need to do is loop each sheet and setup a new workbook to copy original sheet.

$WorkBook.Sheets | %{
    # Setup new workbook path and name
    $NewWorkBookPath = "$PWD\$($WorkBook.Name)_$($_.Name).xlsx"
    # add new workbook in excel
    $NewWorkBook = $Excel.Workbooks.Add()
    # copy sheet to the new workbook
    $_.Copy($NewWorkBook.Sheets.Item(1))
    # new workbook always have 3 blank sheets by default, below code to remove them
    2..$NewWorkBook.Sheets.Count | %{
        $NewWorkBook.Sheets.Item(2).Delete()
    }
    # save the new workbook to file
    $NewWorkBook.SaveAs($NewWorkBookPath)
    # close new workbook
    $NewWorkBook.Close()
}

At last, close old workbook and excel.

$WorkBook.Close()
$Excel.Quit()

But, things not over yet, some might notice there is a excel.exe process still stays in task manager even we closed powershell. in other programme languages will encounter the same problem, the way to quiet excel.exe is described in https://technet.microsoft.com/en-us/library/ff730962.aspx

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null

Til now all jobs done, more developments to make the script better is not in the scope, so finished by now.

VBA

Another way to achieve the goal is VBA, open a excel and press Alt + F11 you can open VBA editor, if you can‘t you must forgot intall it when you install office.

The way in VBA is quite same like powershell, actually just with different objects.

Sub SplitSheets()
    Application.DisplayAlerts = False
    For Each Sheet In Sheets
        NewWorkBookPath = ActiveWorkbook.FullName & "_" & Sheet.Name & ".xlsx"
        Set w = Workbooks.Add
        Sheet.Copy w.Sheets.Item(1)
        For i = 2 To w.Sheets.Count
            w.Sheets.Item(2).Delete
        Next
        w.SaveAs NewWorkBookPath
        w.Close
        Set w = Nothing
    Next
End Sub

It‘s just a macro, in workbook view use Alt + F8 can quick invoke macro commands, in the VBA editor view, just press F5.

- Larry

时间: 2024-10-29 03:02:50

[Powershell / VBA] To split Excel sheets to individual workbooks.的相关文章

【VBA研究】EXCEL启动时自动启动窗体

作者:iamlaosong VBA编程时为了界面美观,我们经常用到窗体Form,那么,如何做到让VBA窗体在EXCEL启动时自动运行呢? 方法有二,第一,双击ThisWorkbook,输入以下代码(Open事件): Private Sub Workbook_Open() UserForm1.Show End Sub 第二,也可以插入一个模块,输入下面自启动代码: Sub Auto_Open() UserForm1.Show End Sub 两种方法都可以启动VBA窗体.上面两个过程其实就是一个自

使用VBA批量转换Excel格式,由.xls转换成.xlsx

问题分析: Excel2007以前的格式是.xls,之后的格式是.xlxs.打开单独的一个Excel文档,使用“另存为”功能,可以很轻松的转换格式.但是面对几百个Excel表这样就太累了,搜索很久,也没发现一个工具可以直接批量进行格式转换. 最终发现可以使用VBA来实现批量转换Excel格式的功能.大家不要被吓到,VBA我也不懂,代码是从别人那里搞到的,现在也只是知道了怎么使用,但这足够解决问题了 VBA介绍: 1.VBA是一种编程语言,它依托于Office软件,不能独立的运行,通过VBA可以实

VBA bat create excel files

the database is current excel when you click "create" button, then create excel by customer code . in the data source have a lot of data,contains customer code and the detail info . one customer code point many detail info each a customer code c

[VBA] 如何 隐藏 Excel 主窗口

我们可以利用隐藏主窗口的方式要求使用者输入账号密码,如下图 由上图得知Excel已经在执行了,但是主要的应用程序窗口被藏起来了. 1.隐藏的方式其实很简单只要设定Application.Visible = True 属性即可 2.或是利用下列属性,将主窗口移出屏幕 Application.WindowState = xlNormal Application.Left = 10000 如何隐藏 Excel 主窗口 1.利用Workbook_Open事件,使Excel一执行后便隐藏主程序画面 Pri

[Powershell / VBA] 把excel中的表分离成独立的excel文件

This article also published in Eng @ http://www.cnblogs.com/LarryAtCNBlog/p/4441201.html 今天在两个地方看到了这样一个问题:把一个excel中的表复制出来另存为一个独立的excel文件.其中一个是cnblog,另一个想不起来了.想到自己将来也可能遇到这样的问题,于是用powershell做了一个脚本以备不时之需. Powershell 当然,首先要有一个excel文件包括了一堆表. 用脚本自动化excel最常

利用VBA Hack掉Excel的保护密码

1.录制新宏. 2.停止录制 3.删除宏内原有所有内容 4.粘贴以下代码进去 5.运行宏. 6.OK! Public Sub AllInternalPasswords() ' Breaks worksheet and workbook structure passwords. Bob McCormick ' probably originator of base code algorithm modified for coverage ' of workbook structure / wind

利用VBA批量给Excel添加超链接

主要思想是先给单元格设置名称,再设置超链接 代码如下: Sub creat_link() Dim Source As String Source = "t1" Dim Target As String Target = "t2" Dim i As Integer i = 1 Dim j As Integer j = 1 Do While i < 10 Dim Svalue As String Svalue = Sheets(Source).Cells(i, 1

【一步一步学习VBA】将Excel内容导出为单个txt文件

这里我就直接上源码: Sub 导出txt1() Dim file As String, arr, i '定义文本文件的名称 file = ThisWorkbook.Path & "\新工资表.txt" '判断是否存在同名文本文件,存在先行删除 If Dir(file) <> "" Then Kill file '将当前的数据读入数组 arr = Sheet1.Range("a1").CurrentRegion '使用print

vba 数字变为excel对应列的字母

Public Function GetColName(ByVal y As Integer) As String       Dim z     As Integer       Dim i     As Integer       Dim n(25)     As String For i = 0 To 25               n(i) = Chr(65 + i)       Next If y <= 26 Then         GetColName = n(y - 1)