1
代碼運行良好,同時檢查工作簿文件是否存在由對話框打開的「Test_Worksheet」工作表。如果「Test_Worksheet」工作表存在於該文件中,則工作簿文件正確打開&,然後debug.print(在Sub ChkSalfile中)給出「Name is True」。訂閱超出範圍錯誤
但是,如果表在Workbook中不可用,那麼會出現「訂閱超出範圍」錯誤。請幫忙。我的代碼如下
Sub Main()
Dim salefor As Workbook
Dim salpathfileName As String, salfileName As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
.InitialFileName = "*SAL*.*"
result4 = .Show
If (result4 <> 0) Then
salfileName = Dir(.SelectedItems(1))
salpathfileName = .SelectedItems(1)
Else
'if user pressed CANCEL - exit sub
Application.ScreenUpdating = True
MsgBox "User pressed CANCEL"
Exit Sub
End If
End With
Set salefor = Workbooks.Open(salfileName, ReadOnly:=True)
Call ChkSalfile(salfileName, salefor)
End Sub
Sub ChkSalfile (salfileName As String, salefor As Workbook)
Dim chksalsheet As String
chksalsheet = DoesWorkSheetExist("Test_Worksheet", salfileName)
If chksalsheet = True Then
Debug.Print "Name is " & chksalsheet
Else
Debug.Print "File not found"
End If
End Sub
Option Explicit
Public Function DoesWorkSheetExist(WorkSheetName As String, Optional WorkBookName As String)
Dim WS As Worksheet
On Error Resume Next
If WorkBookName = vbNullString Then
Set WS = Sheets(WorkSheetName)
Else
Set WS = Workbooks(WorkBookName).Sheets(WorkSheetName)
End If
On Error GoTo 0
DoesWorkSheetExist = Not WS Is Nothing
End Function
哪一行拋出「認購超出範圍「錯誤? – user3598756
「Test_worksheet」不存在時出現錯誤。我認爲çhksalsheet(在chkSalFile下)變量沒有得到定義,當沒有找到工作表。 – vts
哪一行是拋出該錯誤?單擊錯誤消息框中的「調試」按鈕,然後將其帶到突出顯示的那一行 – user3598756