0

我在下面创建了这个示例来说明和解释我的需求。我想用 A 列中的结果完成 A 和 B(包括 A 和 B)之间的数字范围,并为创建的每个新行保留 C 中的数据。

当前表:

   A    |    B     |    C     
-------------------------------
0010    |  0015    |   0312
0020    |          |   3500
0029    |  0031    |   4000

期望的结果:

   A    |    B     |    C     
-------------------------------
0010    |          |   0312
0011    |          |   0312
0012    |          |   0312
0013    |          |   0312
0014    |          |   0312
0015    |          |   0312
0020    |          |   3500
0029    |          |   4000
0030    |          |   4000
0031    |          |   4000

注意:结果不需要在同一张表中呈现。

有什么建议么?

编辑:

有人几乎解决了它,但删除了他们的帖子,同时我设法把它搞砸了。谁能帮我发现错误?

Sub Macro1()

Dim num, i, j, x, lastRow

Dim sh1 As Worksheet
Dim sh2 As Worksheet
Set sh1 = ThisWorkbook.Sheets("Sheet1")
Set sh2 = ThisWorkbook.Sheets("Sheet2")

lastRow = sh1.Cells(Rows.Count, "A").End(xlUp).Row

x = 1
For i = 2 To lastRow
    num = (sh1.Cells(2, 2) - sh1.Cells(2, 1))
        For j = 0 To num - 1
            x = x + 1
            sh2.Cells(x, 1) = sh1.Cells(i, 1) + j
            sh2.Cells(x, 3) = sh1.Cells(i, 3)
        Next j
Next i

End Sub

修复上述内容后,唯一缺少 A 列中最后一个值的内容。在我的示例中运行此命令时,A 中的结果是:

0010
0011
0012
0013
0014

它应该是:

0010
0011
0012
0013
0014
0015
4

2 回答 2

1

这是假设您的数据位于 A、B 和 C 列中名为“Sheet1”的工作表上,您的数据从第 2 行开始向下。它将在“Sheet2”上生成您的输出:

Sub Macro1()

Dim num, i, j, x, lastRow

Dim sh1 As Worksheet
Dim sh2 As Worksheet
Set sh1 = ThisWorkbook.Sheets("Sheet1")
Set sh2 = ThisWorkbook.Sheets("Sheet2")

lastRow = sh1.Cells(Rows.Count, "A").End(xlUp).Row

x = 1
For i = 2 To lastRow
    If sh1.Cells(i, 2) = "" Then
        num = 0
    Else
        num = (sh1.Cells(i, 2) - sh1.Cells(i, 1))
    End If
    For j = 0 To num
        x = x + 1
        sh2.Cells(x, 1) = sh1.Cells(i, 1) + j
        sh2.Cells(x, 3) = sh1.Cells(i, 3)
    Next j
Next i

End Sub
于 2013-10-16T12:59:59.830 回答
0

首先,您将单元格格式更改为文本,然后使用此代码

Sub test()
Dim a, rw, b As Long
rw = 1
For a = 1 To Sheet1.Cells(1048576, 1).End(xlUp).Row
    If Sheet1.Cells(a, 2) = "" Then
        Sheet2.Cells(rw, 1) = Sheet1.Cells(a, 1)
        Sheet2.Cells(rw, 3) = Sheet1.Cells(a, 3)
        rw = rw + 1
    ElseIf Sheet1.Cells(a, 2) <> "" Then
        For b = Val(Sheet1.Cells(a, 1)) To Val(Sheet1.Cells(a, 2))
            Sheet2.Cells(rw, 1) = Format(b, "0000")
            Sheet2.Cells(rw, 3) = Sheet1.Cells(a, 3)
        rw = rw + 1
        Next
    End If
Next

End Sub
于 2013-10-16T12:59:26.817 回答