空白单元格中的自动填充月份

时间:2013-11-08 08:08:05

标签: excel vba

我有问题如何改进我的宏来通过A列,当它找到空白单元格然后它会输入那个月的名字?我尝试过类似下面的内容,但只能使用Range("A1").value代替Cells(Rows.Count, "A").End(xlUp).Row

 Sub actual_month()
'fill month col

Dim arrMonths() As String
ReDim arrMonths(1 To 12)

Application.DisplayAlerts = False
arrMonths(1) = "JAN"
arrMonths(2) = "FEB"
arrMonths(3) = "MAR"
arrMonths(4) = "APR"
arrMonths(5) = "MAY"
arrMonths(6) = "JUNE"
arrMonths(7) = "JULY"
arrMonths(8) = "AUG"
arrMonths(9) = "SEP"
arrMonths(10) = "OCT"
arrMonths(11) = "NOV"
arrMonths(12) = "DEC"

Workbooks("UAC_report_p.xlsb").Activate

Sheets("SLA Calculation").Select


For Each Cell In ActiveSheet.UsedRange.Cells
      'do some stuff
   Next



For i = 1 To 12



Cells(Rows.Count, "A").End(xlUp).Row = Month(Date)
  If Cells(Rows.Count, "A").End(xlUp).Row.Value = Month(Date) Then _
     Cells(Rows.Count, "A").End(xlUp).Row.Value = arrMonths(Cells(Rows.Count, "A").End(xlUp).Row.Value)
   Next i




Application.DisplayAlerts = True
End Sub

1 个答案:

答案 0 :(得分:1)

假设您正在使用当前月份,您可以这样做

Public Sub test()
    Dim endrow As Long
    Dim ws As Worksheet
    Dim Col As Long
    Dim arrMonths(1 To 12)

    arrMonths(1) = "JAN"
    arrMonths(2) = "FEB"
    arrMonths(3) = "MAR"
    arrMonths(4) = "APR"
    arrMonths(5) = "MAY"
    arrMonths(6) = "JUNE"
    arrMonths(7) = "JULY"
    arrMonths(8) = "AUG"
    arrMonths(9) = "SEP"
    arrMonths(10) = "OCT"
    arrMonths(11) = "NOV"
    arrMonths(12) = "DEC"

    Set ws = Sheet4

    'set column to "A"
    Col = 1


    endrow = ws.Cells(ws.Rows.Count, Col).End(xlUp).Row + 1

    If ws.Cells(endrow, Col).Value = "" Then _
    ws.Cells(endrow, Col).Value = arrMonths(Month(Now))
End Sub

修改

更好的方法是根本不使用数组,并使用LanguageID获取特定语言中月份名称的等效项。有关LanguageID的完整列表,请参阅THIS LanguageID English_United_States409

试试此代码

Public Sub test()
    Dim ws As Worksheet
    Dim Lrow As Long, Col As Long
    Dim sMonth As String

    Set ws = Sheet4

    '~~> Not sure if Czech has same names as `Text` / `Today`. 
    '~~> If not then replace `Text` and `Today` with their respective equivalents.
    sMonth = Application.Evaluate("=TEXT(TODAY(),""[$-409]MMM"")")

    With ws
        '~~> Set column to "A"
        Col = 1

        Lrow = .Cells(.Rows.Count, Col).End(xlUp).Row + 1

        If .Cells(Lrow, Col).Value = "" Then _
        .Cells(Lrow, Col).Value = sMonth
    End With
End Sub