VBS遍历Excel工作表的实现代码
核心代码
'****************************************** '拖拽文件,获取文件路径 '****************************************** Ifwscript.Arguments.count=0then msgbox"拖拽文件到本图标",0,"提示" Endif fora=0towscript.Arguments.count-1 strPath=wscript.Arguments(a) next '****************************************** '定义Excle对象、工作薄对象、工作表对象 '****************************************** dimoExcel,oWb,oSheet setws=WScript.createobject("wscript.shell") SetoExcel=CreateObject("Excel.Application") '打开指定的工作簿 SetoWb=oExcel.Workbooks.Open(strPath) '显示打开的Excel工作簿 oExcel.visible=true '****************************************** '遍历工作簿的所有工作表 '****************************************** forj=1tooWb.sheets.count setoSheet=oWb.Sheets(j) '选中并激活工作表 oSheet.Activate oSheet.Range("A1")="成功" next
Excel遍历所有工作簿中所有工作表执行宏
Subtest() n=Worksheets.Count Fori=1Ton Worksheets(i).Activate Macro1 Next EndSub
Macro1是宏的名称
使用VBS遍历EXCEL
DimxlApp,xlSheet,xlWorkBookDimiRowCount,iLoop,jLoop,jColumnCount,numAdd SetxlApp=CreateObject("Excel.Application") xlApp.Visible=True SetxlWorkBook=xlApp.Workbooks.Open("C:\data.xls") SetxlSheet=xlWorkBook.Sheets("Sheet1") iRowCount=xlSheet.UsedRange.Rows.Count jColumnCount=xlSheet.UsedRange.Columns.Count ForiLoop=1ToiRowCount ForjLoop=1TojColumnCount MsgBox(xlSheet.cells(iLoop,jLoop).value) Next Next xlWorkBook.Save xlWorkBook.Close xlApp.Quit
VBScript编写自动Excel文件内容到数组并提示输出
解压到任意目录,点击VBS文件执行,程序自动读取文件所在目录的Excel文件到数组中,并通过提示框逐个输出,提示框1s自动关闭。
DimoExcel,oWb,oSheet SetoExcel=CreateObject("Excel.Application") SetoWb=oExcel.Workbooks.Open(dir&"\DataReport.xls") SetoSheet=oWb.Sheets("HistoryData") Dimi Dima(150) Fori=5To145'145-5+1=141 a(i-5)=oSheet.Range("B"&i).Value print"data=",a(i-5) next SetoSheet=Nothing oExcel.Workbooks.Close oExcel.Quit'关闭excel.exe' FunctionDir() SetWshShell=CreateObject("Wscript.Shell") Dir=WshShell.CurrentDirectory EndFunction Functionprint(prompt,title) SetWshShell=CreateObject("Wscript.Shell") WshShell.Popupprompt&title,1,"" EndFunction
为了方便学习特将代码打包提供下载 下载地址