[英]Runtime error “9” in VBA[excel] - Subscript out of range
I am currently working on a code that takes the date from the user, opens a calendar, sees if the month is present, and if it isn't, creates a worksheet with that month name. 我目前正在使用一个代码,该代码从用户那里获取日期,打开日历,查看是否存在月份,如果不存在,则创建具有该月份名称的工作表。
The code looks like this where m_y is a string, and has values such as "January 2014" [the " signs included]: 代码看起来像这样,其中m_y是一个字符串,并具有诸如“ January 2014” [[包括“符号”的值:
Sub addmonth(m_y)
On Error Resume Next
CalendarWorkbook.Worksheets(m_y).Select
If Err.Number<>0 Then
'code to add sheet and format it
I tried putting it in a With/End With command, I have no Option Explicit in the code. 我尝试将其放在With / End With命令中,代码中没有Option Explicit。 Other methods mentioned in answers such as using the
.Range()
instead of the .Select
; 答案中提到的其他方法,例如使用
.Range()
代替.Select
; however I had no luck in succeeding. 但是我没有成功的运气。
Any help provided would be appreciated. 提供的任何帮助将不胜感激。
.Select
in most cases is the main cause of runtime errors. 在大多数情况下,
.Select
是运行时错误的主要原因。 I believe you have another workbook open. 我相信您还有另一本工作簿。 INTERESTING READ
有趣的阅读
Try this another way which doesn't use .Select
尝试另一种不使用
.Select
Option Explicit
Sub test()
addmonth ("""Feb2015""")
End Sub
Sub addmonth(m_y)
Dim calendarworkbook As Workbook
Dim ws As Worksheet
Set calendarworkbook = ThisWorkbook
On Error Resume Next
Set ws = calendarworkbook.Worksheets(m_y)
On Error GoTo 0
If ws Is Nothing Then calendarworkbook.Worksheets.Add.Name = m_y
End Sub
Note : OERN (On Error Resume Next) should be used judiciously. 注意 :应谨慎使用OERN(错误恢复下)。 Ensure that it just curbs the message for only the part that you want and not for the rest.
确保仅限制您想要的部分而不是其余部分的消息。 Else it is not good error handling :)
否则它不是很好的错误处理:)
This worked for me 这对我有用
Sub test()
addmonth ("""Feb2015""")
End Sub
Sub addmonth(m_y)
Dim calendarworkbook As Workbook
Set calendarworkbook = ThisWorkbook
On Error Resume Next
calendarworkbook.Worksheets(m_y).Select
If Err.Number <> 0 Then
With calendarworkbook.Worksheets.Add
.Name = m_y
End With
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.