运行VBA脚本后“重置”集合

时间:2018-11-14 09:52:11

标签: excel vba excel-vba

我不确定VB为何要这样做,因为我经验不足。基本上,我第一次运行脚本时,输出是我期望的,但是第二次它看起来完全错误。

代码如下:

'define queue type
Dim Queue As New Collection


'define job list
Dim JobList As New Collection

'loop parameters
Dim rng As Range, rng2 As Range
Dim rng_w As Range, rng_w2 As Range

Dim TimeRange As Double




'loop over list and get jobs at frequency
Dim i As Double
Dim j As Integer



Sub Generate_Queue()
ThisWorkbook.Sheets("AGV capacity").Activate
Set rng = Range("L6:L7")
Set rng2 = Range("M6:M7")

'fill JobList

Dim Frequencies As Range
Set Frequencies = rng
Dim Jobs As Range
Set Jobs = rng2
Dim dividend

TimeRange = ThisWorkbook.Sheets("AGV capacity").Range("O6") * 3600



For i = 1 To rng.Count
    Set tmp = New Transport
    tmp.Frequency = (TimeRange / Frequencies(i))
    tmp.SourceDest = Jobs(i)
    JobList.Add tmp
Next i

i = 1

'while loop over time range (e.g. 24 hours)
While i < TimeRange
    'for loop over number of entries in job list
    For j = 1 To JobList.Count
        'check if i is mod Frequency, meaning it should be added to the queue
        If ((i Mod JobList(j).Frequency) = 0) Then
            Set tmp = New Transport
            dividend = (i / JobList(j).Frequency)

            tmp.Frequency = ((dividend * JobList(j).Frequency) / 3600)
            tmp.SourceDest = JobList(j).SourceDest
            Queue.Add tmp
        End If
    Next j
i = i + 1
Wend

ThisWorkbook.Sheets("order queue").Activate
Set rng_w = Range("A2", "A" & Queue.Count)
Set rng_w2 = Range("B2", "B" & Queue.Count)

i = 1

For i = 1 To 1000
    rng_w(i).Value = ""
    rng_w2(i).Value = ""

Next i

For i = 1 To Queue.Count
    rng_w(i).Value = Queue(i).Frequency
    rng_w2(i).Value = Queue(i).SourceDest

Next i  
End Sub

我正在使用两个不同的Excel工作表,但是在两次运行中读取的数据保持不变。当我观看不同的集合时,它们会使用相同的数据集进行更改,有时甚至会创建两次!来自其他语言,我希望它们在每次运行时都将被删除,但事实并非如此。如何“重置”这些对象?

1 个答案:

答案 0 :(得分:1)

答案是,在使变量变暗时,尤其是在过程外部定义变量时,不要使用New关键字,因为您不直接控制何时将其实例化。

如果需要Queue和JobList才能更广泛地使用,那么它们会在正确的位置定义,但是当您执行Generate_Queue时,可能是您应该实际创建变量的时候。

因此,在模块顶部:

Dim Queue As Collection
Dim JobList As Collection

在Generate_Queue中:

Set Queue = New Collection
Set JobList = New Collection

因此,每次调用Generate_Queue时,都会重新创建这两个变量(如果您要执行此操作)。