*************************************************** 原文: blog.csdn.net/clark_xu 徐长亮的专栏** 微信公众号:clark_blog *************************************************
一、创建WScript 对象
'创建excel对象
dim xlsApp
set xlsApp = CreateObject("Excel.Application")
xlsApp.Visible = True
'创建文件对象
dim fileapp
set fileapp=CreateObject("Scripting.FileSystemObject")
二、Excel对象
dim xlsApp dim xlsWorkBook dim xlsSheet
set xlsApp = CreateObject("Excel.Application") xlsApp.Visible = True 'workbooks对象 set xlsWorkBook=xlsApp.Workbooks.open("E:\15-VB\1001_20150810.xls")
set xlsSheet=xlsWorkBook.sheets(1)
'--Workbooks对象 '--open 'xlsApp.WorkbooKs.Open FileName:='',ReadOnly:=
'sheets对象 'Sheets集合可以包含图表或工作表对象。 '打印机打印 'xlsApp.sheets.printout '添加sheets页 'xlsapp.Sheets.Add xlsWorkBook.sheets.add '激活 'xlsSheet.Activate 'or xlsWorkBook.sheets(1).activate
'新建,默认前方 'xlsapp.Worksheets.Add '索引 隐藏 'xlsWorkBook.Worksheets(3).Visible = False
三、文件操作
dim fileapp dim folderdir dim folderobject dim i dim filename set fileapp=CreateObject("Scripting.FileSystemObject") '不能加set folderdir=InputBox("文件夹路径,例如E:\15-VB", MsgTitle) 'msgbox folderdir '文件对象 set folderobject=fileapp.GetFolder(folderdir)
'for each语句 for each i in folderobject.files msgbox i.name msgbox i.type 'if判断 if i.type="Microsoft Office Excel 97-2003 工作表" then msgbox "是excel" end if next
四、脚本:
dim xlsApp 'wls对象 dim xlsWorkBook 'workbook对象 dim xlsSheet 'worksheet对象 dim xlscon 'connection对象 dim xlsquery 'querytable对象 dim i 'connection基数 dim j '内部循环
dim fileapp dim folderdir dim folderobject dim filename 'wls对象 set xlsApp = CreateObject("Excel.Application") xlsApp.Visible = True set fileapp=CreateObject("Scripting.FileSystemObject") '不能加set folderdir=InputBox("文件夹路径,例如E:\15-VB", MsgTitle) 'msgbox folderdir '文件对象 set folderobject=fileapp.GetFolder(folderdir) 'for each语句 for each i in folderobject.files 'set filename=i.name 'Microsoft VBScript 运行时错误: 缺少对象: '[string: "vbs"]' '不能加set '文件名中带.,取文件类型失效 'filename=right(i.NAME, Len(i.name) - InStr(i.name, ".")) 'msgbox i.name 'msgbox filename 'if判断 if i.type="Microsoft Office Excel 97-2003 工作表" then '文件名中带.失效, 'if filename="xls" or filename="xlsx" then msgbox "是excel" '不能用set 否则报错缺少对象 filename=folderdir&"\"&i.name 'msgbox filename 'workbooks对象 set xlsWorkBook=xlsApp.Workbooks.open(filename) 'for next循环 for j=1 to xlsWorkBook.connections.count set xlscon=xlsWorkBook.connections(j) 'msgbox xlscon.application 'Micosoft excel' msgbox xlscon xlscon.refresh 'On Error Resume Next next xlsWorkBook.Save end if next '退出操作 xlsWorkBook.Close xlsApp.Quit Set xlsApp = Nothing '释放Excel对象 Set xlsWorkBook = Nothing '释放内存 set folderobject=Nothing set fileapp=Nothing