Excel VBA:遍历列表并生成报告

时间:2018-10-10 00:43:56

标签: excel vba excel-vba loops

我正在努力解决我认为是循环的问题。我更像是使用Excel VBA的“后院机械师”,所以请原谅我的简单问题。

不幸的是,由于专有信息,我无法共享工作簿,但是我拥有用于​​某些字段名称更改的代码。

背景:我有一列,每次只能使用1个单元格,并将其输入到数据透视表字段中并运行报告。现在,我删除了当前行,该行将引用返回到单元格A2。可以将其视为编程的Pez分配器。我知道这很糟糕而且很蛮​​力。行删除操作占用大量系统资源,我想对其进行优化。在过去的几个小时里,我尝试阅读这里和其他一些网站,但我无法一目了然。

任何帮助将不胜感激!

Sub AutoReport()

Dim strPage As String



Worksheets("HomePage").Select

Beginning:
'Sets the name in Home Page to the name in Feederlist cell F2

With Sheet1
    strPage = Worksheets("FeederList").Range("A2")
    Worksheets("HomePage").PivotTables("PivotTable1").PivotFields("UNIQUE ID"). _
    CurrentPage = strPage
End With


**Do a Bunch of Stuff**



' Feeds the next input into the machine

MoveToNext:

Worksheets("FeederList").Activate
Worksheets("FeederList").Range("A2").EntireRow.Delete

If Worksheets("FeederList").Range("A2") = "" Then

MsgBox "All Reports have been created.", vbInformation + vbOKOnly

Exit Sub
Else

GoTo Beginning

End If


End Sub

1 个答案:

答案 0 :(得分:0)

接受是学习的第一步。通常,stackoverflow社区通过提供解决方案而非确切的解决方案的提示来鼓励大脑的技术和逻辑部分。但是,由于您是个新手,所以我先给出提示,然后再讲代码以纠正您的问题。您的代码进展顺利,但是一些小的调整将极大地优化您的代码。


Worksheets("HomePage").Select

Dim lstRow As Long
Dim rngCell As Range
Dim rngSelection As Range

'Let's find the last row with data in column A. 
'So that we only traverse the required range without the need of 
'deleting previous cells while using the For loop.
lstRow = Worksheets("FeederList").Range("A" & Application.Rows.Count).End(xlUp).Row
Set rngSelection = Worksheets("FeederList").Range("A2:A" & lstRow)

For Each rngCell In rngSelection.Cells
    'Ignore all the cells with blank value or else the pivot table will throw the error
    If Trim(rngCell.Value) <> vbNullString Then
        'Sets the name in Home Page to the name in Feederlist cell F2
            strPage = rngCell.Value
            Worksheets("HomePage").PivotTables("PivotTable1").PivotFields("UNIQUE ID"). _
            CurrentPage = strPage

        '   **Do a Bunch of Stuff**

    End If
Next
rngSelection.Clear ' Optional - if the range really needs to be cleared
MsgBox "All Reports have been created.", vbInformation + vbOKOnly

您需要了解所做的更改,并可能提出任何其他问题。以下是对原始代码所做的更改。

  • 介绍了A列中包含一些数据的最后一个单元格的计算方法
  • 引入了For Loop而不是使用标签,从而无需删除行