输入以逗号分隔的年份,年份岛屿列表,转换为VBA中的年份列表

时间:2018-03-21 22:47:22

标签: excel excel-vba excel-2010 vba

我正在尝试将年份和年份范围列表验证为年份列表。例如,如果用户输入:

1946, 1948, cat, 1950-1954, dog, 1960

我希望VBA将其解析为列表:

1946, 1948, 1950, 1951, 1952, 1952, 1953, 1954, 1960

然后我将使用年份修改工作表上的特定单元格。

我可以通过分割逗号然后在使用列表时验证数值来轻松处理猫狗:

Sub customYearList
 customListEntry = InputBox("Enter list of years to activate")

 customList = Split(customListEntry, ",")

       For Each cYear In customList
          If IsNumeric(cYear) Then
               [[use the year to reference a WS.cell(myRow, cYear) ]]
          end if
       Next
End sub

我无法弄清楚如何捕捉破折​​号,并在其间填写。 Psuedocode为我所描绘的:

if cYear[i] = "-"
    act on all integer values from cYear[i-1] to cYear[i+1]  

但是我的列表引用甚至没有像这样修改的索引。而且会有一些有趣的循环。

FWIW

  • 有效年份将始终在1946年至2050年之间。所有这些年都是 在第13行中列出。
  • 最终目标是,如果年份在自定义列表中,则在第12行(即年度上方)更改为1,如果年份不在,则更改为0

我在搜索时遇到问题,因为我无法在不使用重载术语"范围"的情况下思考如何描述它。

1 个答案:

答案 0 :(得分:1)

这可以完成您正在寻找的内容,但可以添加额外的错误控制,以确保在年份列表中没有重复(如果这是一个问题)。对最终结果进行排序是另一个未解决的选项,但有许多简单数组排序的例子。

Sub customYearList()
    Dim i As Long, mny As Long, mxy As Long, y As Long, customListEntry As String
    Dim tmp As Variant, customList As Variant, yearList As Variant

    mny = 1946: mxy = 2050
    customListEntry = InputBox("Enter list of years to activate")
    'customListEntry = Sheet1.Cells(2, 1).Value

    customList = Split(customListEntry, ",")
    ReDim yearList(0)
    For i = LBound(customList) To UBound(customList)
        If IsNumeric(customList(i)) Then
            If CLng(customList(i)) >= mny And CLng(customList(i)) <= mxy Then
                yearList(UBound(yearList)) = CLng(customList(i))
                ReDim Preserve yearList(UBound(yearList) + 1)
            End If
        ElseIf CBool(InStr(1, customList(i), Chr(45))) Then
            tmp = Split(customList(i), Chr(45))
            If IsNumeric(tmp(LBound(tmp))) And IsNumeric(tmp(UBound(tmp))) Then
                For y = CLng(tmp(LBound(tmp))) To CLng(tmp(UBound(tmp)))
                    If y >= mny And y <= mxy Then
                        yearList(UBound(yearList)) = y
                        ReDim Preserve yearList(UBound(yearList) + 1)
                    End If
                Next y
            End If
        End If
    Next i
    ReDim Preserve yearList(UBound(yearList) - 1)

    Sheet1.Cells(3, "B").Resize(1, UBound(yearList) + 1) = yearList
End Sub