简体   繁体   English

Excel VBA初学者-获取运行时错误'9'下标超出范围

[英]Excel VBA Beginner - Getting Run time error '9' Subscript out of range

I am trying to write a simple macro to change a date format mm/dd/yy to just the month full name. 我正在尝试编写一个简单的宏,以将日期格式mm / dd / yy更改为仅月份的全名。 This is what I have using a days worth experience in VBA. 这就是我过去几天在VBA中值得使用的经验。 I'm missing the error here 我在这里错过了错误

Sub ChangeDate()

    Dim Last As Integer
    Last = Cells(Rows.Count, 1).End(xlUp).Row
    Dim Counter As Integer

    For Counter = 2 To Last
        Dim Month As String
        Month = Left(Worksheets("Sheet1").Cells(Counter, 2), 1)

        If Month = "7" Then
            Worksheets("Sheet1").Cells(Counter, 2).Value = "July"

        ElseIf Month = "8" Then
            Worksheets("Sheet1").Cells(Counter, 2).Value = "August"

        ElseIf Month = "9" Then
            Worksheets("Sheet1").Cells(Counter, 2).Value = "September"
        End If

    Next Counter

End Sub

Try using this code: 尝试使用以下代码:

Sub ChangeDate()
    Dim Counter As Long
    Dim Last As Integer

    Worksheets("Sheet1").Select
    Last = Cells(Rows.Count, 1).End(xlUp).Row

    For Counter = 2 To Last
        Dim Month As String
        Month = Left(Worksheets("Sheet1").Cells(Counter, 1), 1)

        If Month = "7" Then
        Worksheets("Sheet1").Cells(Counter, 2).Value = "July"

        ElseIf Month = "8" Then
        Worksheets("Sheet1").Cells(Counter, 2).Value = "August"

        ElseIf Month = "9" Then
        Worksheets("Sheet1").Cells(Counter, 2).Value = "September"
        End If
    Next Counter
End Sub

This code reads the date in column 1 and puts the month in column 2. Is a good advice to use Case statement instead of ElseIf . 此代码在第1列中读取日期,在第2列中显示月份。使用Case语句代替ElseIf是一个很好的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM