代码运行良好,同时检查" Test_Worksheet"工作表存在于由对话框打开的工作簿文件中。工作簿文件正确打开&如果" Test_Worksheet" sheet存在于该文件中,然后debug.print(在Sub ChkSalfile中)给出" Name为True"。
但如果工作簿中没有工作表,那么"订阅超出范围"错误来了。请帮忙。我的代码如下
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
答案 0 :(得分:0)
似乎您在VBA项目编辑器中的设置被设置为中断任何错误。将此设置更改为仅在未处理的错误上中断:
Tools --> Options --> General Tab --> Error Trapping --> check "Break on Unhadled Errors"
也就是说,当Dim
为String
时,请将Boolean
变量设为Dim chksalsheet As Boolean ' <-- Not as String
:
http://sub-domain.domain.com:5000/webhook