将单元格值添加到列表中,填充单元格而没有难以解释的空单元格。(见说明图片)

Add cell values to a list, filling cells without empty cells difficult to explain. (see picture in description)

提问人:Sidvi 提问时间:11/1/2017 最后编辑:CœurSidvi 更新时间:6/14/2018 访问量:39

问:

我正在做一个项目,我希望最终用户能够检查他们需要的项目。然后,需要将已勾选的项目添加到项目旁边的列表中。我遇到的问题是,我无法弄清楚如何让 Excel 在不跳过未选中项目的行的情况下将信息添加到行中。这很难解释,但所附的图片准确地表明了我的意思。在列表的末尾应该有一个价格总和,并且这个总和应该始终显示在最后一行数据之后,因此它应该能够根据有多少行数据而移动。所以这是我的问题。

Sub MakeList()
Dim i As Long

    For i = 1 To Rows.Count
        If Cells(i, 4) = True Then
            Cells(i, 6) = Cells(i, 1)
            Cells(i, 7) = Cells(i, 2)
            Cells(i, 8) = Cells(i, 3)
        End If
    Next i

    For i = 1 To Rows.Count
        If Cells(i, 4) = True Then
            Sum = Sum + Cells(i, 3)
        End If
    Next i

    Cells(24, 4) = Sum

End Sub

enter image description here

VBA Excel

评论


答:

0赞 E. Merckx 11/1/2017 #1

一种方法是在每次不包括单元格时添加偏移值。这只是语句部分中的一个简单的计数器。ElseIf

Sub MakeList()

Dim i As Long

Dim Sum As Double
Sum = 0

Dim n As Long
n = 0

For i = 1 To Rows.Count
    If Cells(i, 4) = True Then
        Cells(1 + i - n, 6) = Cells(i, 1)
        Cells(1 + i - n, 7) = Cells(i, 2)
        Cells(1 + i - n, 8) = Cells(i, 3)

        Sum = Sum + Cells(i, 3)
    Else
        n = n + 1
    End If

Next i

    'Place sum at the bottom of the original table
    'Cells(24, 4) = Sum

    'Place sum at the bottom of the output table
    Cells(i + 1 - n, 8) = Sum

End Sub

这会告诉您的代码,每次未包含某个项时,输出都应被该行偏移。我还将求和移到了原始循环中,以避免循环两次。让我知道这是否适合您。

评论

0赞 Sidvi 11/1/2017
它工作得很好,谢谢!不过,我仍然需要将总和添加到列表的末尾?
0赞 E. Merckx 11/1/2017
复制那个,刚看到问题的那句话。请参阅编辑后的答案。它利用了两者的值仍然被存储的事实。ni
0赞 Sidvi 11/1/2017
一个小小的改变,它就起作用了!谢谢!cells(i+1-n+1,8),否则它会将其填充到最后一行。