定义的范围随每个循环而变化(如何停止)

时间:2019-07-08 00:24:26

标签: excel vba

我设置一个范围,然后求和该范围内的每一列。然后,当我测试每个汇总列以检查其值(并删除等于零的值)时,范围会不断变化。我该如何停止或更改它?

基本上,我只想将C到最后一列的每一列相加,如果该列等于零,我想删除该列。我什至根本不需要查看该列的总和。我只想测试它,如果它为零,则删除该列。清理完毕后,我将继续处理数据。我的数据确实有标题。数据中的行数是动态的。如果有更简单的方法,请告诉我。这就是我正在尝试的原因(我的ttlRow之所以看起来像是因为在A列中,我在第一行空白栏中输入了“总计”。

Dim ttlRow As Range
Dim x As Long
Dim y As Long
y = Cells(1, Columns.Count).End(xlToLeft).Column
x = Cells(Rows.Count, 1).End(xlUp).Row
Set ttlRow = Range(Cells(x, 3), Cells(x, y))
Range("C1").End(xlDown).Offset(1, 0).Formula = "=SUM(" & Range(Cells(2, 3), Cells(x - 1, 3)).Address(False, False) & ")"
ttlRow.FillRight

For Each cell In ttlRow
    If cell = 0 Then
        cell.EntireColumn.Delete
    End If
Next

每次运行循环并删除列时,它都会更改ttlRow的长度,因此它永远不会最终遍历所有要检查的列。我该如何解决?

1 个答案:

答案 0 :(得分:1)

使用此功能:

   let marginGuide = contentView.layoutMarginsGuide

    // configure author image
    contentView.addSubview(authorProfileImg)
    authorProfileImg.translatesAutoresizingMaskIntoConstraints = false
    authorProfileImg.widthAnchor.constraint(equalToConstant: 50).isActive = true
    authorProfileImg.heightAnchor.constraint(equalToConstant: 50).isActive = true
    authorProfileImg.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor).isActive = true
    authorProfileImg.topAnchor.constraint(equalTo: marginGuide.topAnchor).isActive = true

    // configure titleLabel //the upper element
    contentView.addSubview(nameLabel)
    nameLabel.translatesAutoresizingMaskIntoConstraints = false
    nameLabel.leadingAnchor.constraint(equalTo: authorProfileImg.trailingAnchor, constant: 10).isActive = true
    nameLabel.topAnchor.constraint(equalTo: marginGuide.topAnchor).isActive = true
    nameLabel.numberOfLines = 1
    nameLabel.font = UIFont(name: "Arial", size: 16)
    nameLabel.text = "name here"
    nameLabel.sizeToFit()

    // configure authorLabel //the lower element
    contentView.addSubview(detailLabel)
    detailLabel.translatesAutoresizingMaskIntoConstraints = false
    detailLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor).isActive = true
    detailLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 5).isActive = true
    detailLabel.sizeToFit()

    detailLabel.numberOfLines = 1
    detailLabel.font = UIFont(name: "Arial", size: 13)
    detailLabel.textColor = UIColor.lightGray
    detailLabel.text = "detail here"

    // configure dateLabel
    contentView.addSubview(dateLabel)
    dateLabel.translatesAutoresizingMaskIntoConstraints = false
    dateLabel.leadingAnchor.constraint(equalTo: detailLabel.leadingAnchor).isActive = true
    dateLabel.topAnchor.constraint(equalTo: detailLabel.bottomAnchor, constant: 5).isActive = true
    dateLabel.sizeToFit()

    dateLabel.numberOfLines = 1
    dateLabel.font = UIFont(name: "Arial", size: 12)
    dateLabel.textColor = UIColor.red
    dateLabel.text = "Jun 5"

    self.sizeToFit()