是否可以在 WSH VBScript(按名称引用)中切换工作簿内的工作表,如果可以,我该怎么做?
这将在已经打开 Excel 文件的脚本中使用。我想访问一个名为“版本控制”的工作表。
以下是我打开工作簿的方式:
xlsFile = path & "\xml-sitemap.xls"
Set objExcel = WScript.CreateObject("Excel.Application")
objExcel.Workbooks.open(xlsFile)
这样就可以了(根据 Ekkehard.Horner 的评论进行了修改)
Dim ws
Dim wb
xlsFile = path & "\xml-sitemap.xls"
Set objExcel = WScript.CreateObject("Excel.Application")
objExcel.Workbooks.open(xlsFile)
Set wb = objExcel.ActiveWorkbook 'the ActiveWorkbook will refer to the opened workbook
Set ws = wb.Worksheets("Version Control") 'ws is a Worksheet object
从 VBScript 自动化 Excel 时,缺少 Excel 提供给 VBA 代码的全局对象。所以一个最小的“工作表”脚本应该如下所示:
Option Explicit
Dim sFSpec : sFSpec = "P:\athto\your.xls"
Dim oExcel : Set oExcel = CreateObject("Excel.Application")
Dim oWB : Set oWB = oExcel.Workbooks.Open(sFSpec)
Dim oWS, sWSName
Set oWS = oWB.Worksheets(1)
sWSName = oWS.Name
WScript.Echo 0, sWSName
Set oWS = oWB.Worksheets(2)
WScript.Echo 1, oWS.Name
Set oWS = oWB.Worksheets(sWSName)
WScript.Echo 2, oWS.Name
oExcel.Quit
使用 VBScript,您可以返回带有“.name”扩展名的 Excel 电子表格的选项卡名称。
Dim excelPath, objExcel, oData, Excel_tab
excelPath = "C:\Users\user.name\Desktop\file.xls"
Set objExcel = CreateObject("Excel.Application")
Set oData = objExcel.Workbooks.Open(excelPath)
Excel_tab = objExcel.ActiveWorkbook.Worksheets(1).name
msgbox(Excel_tab)
objExcel.quit