标题: [文件操作] 求助批处理,Excel只保留第一个工作表 [打印本页]
作者: vanani 时间: 2024-8-16 17:27 标题: 求助批处理,Excel只保留第一个工作表
用AI写了几个都不好用。。
这是AI写的:- @echo off
- setlocal enabledelayedexpansion
-
- rem 设置 Excel 文件路径
- set "excelFilePath=C:\path\to\your\file.xlsx"
-
- rem 使用 WScript 调用 VBA 代码
- cscript //nologo //E:JScript <<EOF
- var excel = new ActiveXObject("Excel.Application");
- excel.Visible = false;
- var workbook = excel.Workbooks.Open("%excelFilePath%");
- var worksheets = workbook.Worksheets;
-
- for (var i = worksheets.Count; i > 1; i--) {
- var sheet = worksheets(i);
- sheet.Delete();
- }
-
- workbook.Save();
- workbook.Close(false);
- excel.Quit();
-
- deleteObject(workbook);
- deleteObject(excel);
-
- function deleteObject(obj) {
- if (obj != null) {
- try { obj.Quit(); } catch(e) {}
- try { obj.Release(); } catch(e) {}
- try { obj = null; } catch(e) {}
- }
- }
- EOF
-
- echo Done.
- pause
- endlocal
复制代码
作者: aloha20200628 时间: 2024-8-16 19:24
本帖最后由 aloha20200628 于 2024-8-17 12:54 编辑
回复 1# vanani
以下代码存为 test.bat 运行...
- @set @v=1 /* &echo off
- set "F=C:\path\to\your\file.xlsx""
- if exist "%F%" cscript /e:jscript "%~f0" "%F%"
- pause&exit/b */
- v=WSH.arguments, x=WSH.CreateObject('excel.application');
- xF=x.workbooks.open(v(0)), w=xF.worksheets, x.displayAlerts=false;
- if (w.count==1) { xF.close(), x.quit(), WSH.quit(); }
- for (var i=w.count; i>0; i--) {
- if (w(i).name.toLowerCase() != 'sheet1') w(i).Delete();
- }
- xF.save(), xF.close(), x.quit(), WSH.quit();
复制代码
作者: ppll2030 时间: 2024-8-16 20:31
回复 1# vanani
把代码保存为vbs文件,跟excel文件放在一起,运行后,该目录下所有excel文件都会删除多余的工作表。- On Error Resume Next
- Set oExcel=WScript.createobject("Excel.Application")
- Set fso=WScript.CreateObject("Scripting.Filesystemobject")
- Set fds=fso.GetFolder(".")
- Set ffs=fds.Files
- For Each ff In ffs
- If (LCase(Right(ff.Name,4))=".xls" Or LCase(Right(ff.Name,4))="xlsx" ) And Left(ff.Name,1)<>"~" Then
- Set owb=oExcel.Workbooks.Open(ff.Path)
- oExcel.DisplayAlerts=False
- For i = owb.Sheets.Count To 2 Step -1
- owb.Sheets(i).Delete
- Next
- owb.Save
- End If
- Next
- owb.Close
- oExcel.Quit
- Set owb = Nothing
- Set oExcel = Nothing
- MsgBox "多余工作表全部删除完毕!"
复制代码
作者: aloha20200628 时间: 2024-8-17 12:56
本帖最后由 aloha20200628 于 2024-8-17 13:22 编辑
回复 1# vanani
2楼代码已订正...
一。如发现只有一张工作表则自动退出
二。sheet1工作表不一定是集合首项,须检查排除...
欢迎光临 批处理之家 (http://www.bathome.net/) |
Powered by Discuz! 7.2 |