0

我有一个脚本可以在一年范围内生成“间隔”年份(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

谢谢!

4

1 回答 1

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-12T15:39:16.593 回答