ObjWorkbook.Worksheets.Count 不工作

ObjWorkbook.Worksheets.Count not working

我正在尝试编写代码来打开 Excel 文件,然后在其中进行搜索。尽管如此,我在检索工作簿中的工作表数量时遇到了问题。我收到错误:

424 - VBScript Runtime Error, Object Required

有什么想法吗?这是我遇到问题的一小部分代码:

Dim Shell : Set Shell = WScript.CreateObject( "WScript.Shell" )
Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim objExcel : Set objExcel = CreateObject("Excel.Application")

Dim myworkbook, worksheetcount
Set myworkbook = objExcel.Workbooks.Open("C:\Temp\Test.xlsx")

On Error Resume Next
Set worksheetcount = myworkbook.worksheets.count 'fails

If Err.number <> 0 Then
    ShowError()
    myworkbook.Close False
End if

Sub ShowError()
    WScript.Echo Err.Number & " Srce: " & Err.Source & " Desc: " & Err.Description
    Err.Clear
End Sub

下面的就可以了。

VBA版本

Dim Shell As Object: Set Shell = CreateObject("WScript.Shell")
Dim oFSO As Object: Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim objExcel As Application: Set objExcel = CreateObject("Excel.Application")

Dim myworkbook As Workbook, worksheetcount As Long
Set myworkbook = objExcel.Workbooks.Open("C:\Temp\Test.xlsx")

On Error Resume Next
worksheetcount = myworkbook.Worksheets.Count

If Err.Number <> 0 Then
    ShowError
    myworkbook.Close False
End If

VBScript 版本

Dim Shell: Set Shell = WScript.CreateObject("WScript.Shell")
Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim objExcel: Set objExcel = CreateObject("Excel.Application")

Dim myworkbook, worksheetcount
Set myworkbook = objExcel.Workbooks.Open("C:\Temp\Test.xlsx")

On Error Resume Next
worksheetcount = myworkbook.Worksheets.Count

If Err.Number <> 0 Then
    ShowError
    myworkbook.Close False
End If

您出错了,因为您试图将 Set 一个值 worksheetcount 不是对象。您仅对对象使用 Set