使用From和To值在Excel中创建新行

时间:2017-09-20 14:45:35

标签: excel function formula

我目前有一张包含两列的工作表 - “从”和“到”。我正在尝试创建一个电子表格,其中每一行都是一个单独的值,该值在当前每行的范围内。

一个例子(抱歉,我还不能嵌入图片) -

我有什么:

enter image description here

我想要的是什么:

enter image description here

3 个答案:

答案 0 :(得分:2)

试试这个VBA代码,

Sub splitToCodes()
Dim i As Long, j As Long, k As Long
j = 2
For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
    If IsNumeric(Cells(i, 1)) Then
        For k = Cells(i, 1) To Cells(i, 2)
            Cells(j, 4) = k
            j = j + 1
        Next k
    Else
        For k = Right(Cells(i, 1), Len(Cells(i, 1)) - 1) To Right(Cells(i, 2), Len(Cells(i, 2)) - 1)
            Cells(j, 4) = k
            Cells(j, 4) = Left(Cells(i, 1), Len(Cells(i, 1)) - Len(Cells(j, 4))) & k
            j = j + 1
        Next k
    End If
Next i
End Sub

enter image description here

此代码循环遍历A列和B列,并在D列中打印输出。根据您的需要进行修改。

注意: - 此代码仅适用于图像中的类似数据,因为您没有提及任何其他格式。

答案 1 :(得分:1)

复制&将FROM和TO列彼此粘贴在一起,并在菜单栏的数据块中应用删除重复功能。

答案 2 :(得分:1)

这是我的超级乏味的解决方案:

Option Explicit
Sub Test()
Dim i As Integer, j As Integer, k As Long, sht As Worksheet, lastrow As Long, missingzeroes As Integer, zeroesholder As String, myzeroes As String
Set sht = ThisWorkbook.Worksheets("Sheet1")
lastrow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

For i = 2 To lastrow
    If IsNumeric(Range("B" & i).Value) = True And IsNumeric(Range("A" & i).Value) = True Then
        j = Range("B" & i).Value - Range("A" & i).Value
        lastrow = sht.Cells(sht.Rows.Count, "D").End(xlUp).Row
            For k = 0 To j
                Range("D" & lastrow + 1 + k).Value = Range("A" & i).Value + k
            Next k
    Else
        j = Right(Range("B" & i).Value, 4) - Right(Range("A" & i).Value, 4)
            lastrow = sht.Cells(sht.Rows.Count, "D").End(xlUp).Row
            For k = 0 To j
                Range("D" & lastrow + 1 + k).Value = Left(Range("B" & i).Value, 1) & Right(Range("A" & i).Value, 4) + k
                If Len(Range("B" & i).Value) <> Len(Range("D" & lastrow + 1 + k).Value) Then
                    missingzeroes = Len(Range("B" & i).Value) - Len(Range("D" & lastrow + 1 + k).Value)
                    zeroesholder = "000000000000000000000000000000000000000000000000000000000000000000"
                    myzeroes = Left(zeroesholder, missingzeroes)
                    Range("D" & lastrow + 1 + k).Value = Left(Range("A" & i).Value, 1) & myzeroes & Right(Range("A" & i).Value, Len(Range("D" & lastrow + 1 + k).Value) - 1) + k
                End If
            Next k
    End If
Next i
End Sub

enter image description here