excel - 如何使用另一列中的值的引用来增加一列中的值

标签 excel vba

我想在 C 列和 D 列中添加 n 个单元格,其中 n 是 B 列中的值

我的代码是:

Sub mycode()
Dim lastrow1 As Long
    lastrow1 = Range("A" & Rows.Count).End(xlUp).Row

Dim lastrow2 As Long
    lastrow2 = Range("C" & Rows.Count).End(xlUp).Row

For h = 2 To lastrow1
    For i = 2 To lastrow2
        If Sheet1.Cells(h, 1).Value = Sheet1.Cells(i, 3).Value Then
            P = 10
            t = i + 1
                For j = 1 To Cells(i, 2).Value
                    Sheet1.Cells(t, 3).Insert shift:=xlDown
                    Sheet1.Cells(t, 4).Insert shift:=xlDown
                    Sheet1.Cells(t, 3).Value = Sheet1.Cells(i, 3).Value
                    Sheet1.Cells(t, 4).Value = Sheet1.Cells(i, 4).Value + P
                    P = P + 10
                    t = t + 1
                Next j
        End If
     Next i
Next h
End Sub

示例输入 1:

Input

运行上面的代码后,输出为

Output after running macro

问题: 现在,当我在第 3 行添加第二个条目并运行代码时,出现了问题:

输入:

enter image description here

代码生成的错误输出:

enter image description here

正确的输出应该是:

enter image description here

我无法确定我的代码哪里出了问题。 请帮忙。

编辑: 样本2: 输入:

enter image description here

输出:

enter image description here

最佳答案

我编辑了您的代码并添加了注释。

更新的代码:

Sub mycode()
Application.ScreenUpdating = False 'Optional speedup code
Dim lastrow1 As Long
lastrow1 = Range("B" & Rows.Count).End(xlUp).Row
Dim Inputs() As Variant         'Create an array to hold positions
ReDim Inputs(lastrow1 - 1)      'Make it big enough to hold all positions
For x = 2 To lastrow1           'For each Position
    Inputs(x - 1) = Cells(x, 4) 'Store The Position
Next x
OutRow = 2      'Row to output to
Increment = 10  'Increment
For Each c In Range("B2:B" & lastrow1) 'For each "count"
    For j = 0 To c.Value
        Cells(OutRow, 3).Value = c.Offset(0, -1).Value 'Put the letter in column C
        If j = 0 Then  'If it's the first new letter, start at the position
            Cells(OutRow, 4).Value = Inputs(c.Row - 1)
        Else 'Otherwise, just add our increment to the number above
            Cells(OutRow, 4).Value = Cells(OutRow - 1, 4).Value + Increment
        End If
        OutRow = OutRow + 1
    Next j
Next c
Application.ScreenUpdating = True 'Optional speedup code
End Sub

最终输出:

Pic4

关于excel - 如何使用另一列中的值的引用来增加一列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37625763/

相关文章:

vba - 当子表单绑定(bind)到表时,是否可以在子表单的表单上引发事件?

VBA - 使用用户定义公式的表上的 Range.Copy 方法错误

excel - 如何在 Excel 中映射对象?

excel - 在链接到其他工作簿时设置变量工作表名称

excel - 将换行后的每个单词分成新行

vba - 平均公式 Excel VBA

excel - Microsoft Excel 2010 复制/粘贴编辑想法和小细节帮助请求

vba - 使用 Excel 中的查找并打开/关闭程序

excel - 计算两个日期每季度的天数

excel - 无法更改单元格值