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

Enter comma-separated list of years, year islands, convert to list of years in 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

我不知道如何同时捕捉破折号,并在中间填充。我所描绘的伪代码:

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

但是我的列表引用甚至没有索引可以那样修改。并且会有一些有趣的循环。

FWIW

我在搜索这个时遇到了问题,因为我想不出如何在不使用重载术语的情况下描述它 "range"。

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

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