【问题标题】:excel: generate missing years of year range into one cellexcel:将缺少的年份范围生成到一个单元格中
【发布时间】:2013-07-11 04:17:34
【问题描述】:

我有一个脚本可以生成一年范围内的“间隔”年份(year_start year_end - 单独的输入),即对于 1997-2002,脚本生成以下内容: 1997,1998,1999,2000,2001,2002 并将每个结果显示在一个新行中(彼此下方)

如何修改它以将结果显示到 一个 单元格(逐行),值用逗号分隔?另外,理想情况下,我应该能够选择整个开始(A)和结束列(B)的内容,然后将结果生成到C列(匹配A和B的行数)。

脚本:

Dim iYear As Integer, iYearS As Integer, iYearE As Integer, iOffset As Integer
Dim oRangeStart As Range

Set oRangeStart = Range("A1")

iYearS = Range("A1")
iYearE = Range("B1")

For iYear = iYearS To iYearE
    oRangeStart.Offset(iOffset, 0).Value = iYear
    iOffset = iOffset + 1
Next

谢谢!

【问题讨论】:

    标签: excel excel-2007 range vba


    【解决方案1】:

    这会将逗号分隔的字符串放在 C 列中,用于在运行宏时选择的任何行。没有错误检查来确保这些行的 A 列和 B 列包含适当的值:

    Sub FillYears()
    Dim ws As Worksheet
    Dim iYear As Integer, iYearS As Integer, iYearE As Integer
    Dim cell As Range
    Dim Years As String
    
    Set ws = ActiveSheet
    For Each cell In Selection.EntireRow.Columns(3).Cells
        iYearS = ws.Cells(cell.Row, 1).Value
        iYearE = ws.Cells(cell.Row, 2).Value
        Years = vbNullString
        For iYear = iYearS To iYearE
            Years = Years & iYear & ","
        Next iYear
        cell.Value = "'" & Left(Years, Len(Years) - 1)
    Next cell
    End Sub
    

    请注意,必须在 C 列中的字符串前面加上单引号,以强制它为文本。否则,至少在美国版本中,Excel 会很有帮助地假设您的意思是它们是千位分隔符,并将它们更改为每三个空格。我以前从未注意到这一点!

    【讨论】:

    • 完美!你救了我的命!谢谢!
    猜你喜欢
    • 2013-07-10
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    相关资源
    最近更新 更多