私有函数跳过循环

时间:2019-06-10 12:36:24

标签: excel vba dictionary

我现在试图了解字典如何在VBA中工作,因此我创建了一个简单的类模块,一个函数,然后创建了两个子控件,但是出于我自己的原因,For循环在该函数中被完全跳过了。以下是上述所有项目的代码。我确实在“工具”>“引用”中选中了Microsoft脚本运行时。我不太了解后期绑定和早期绑定的用法,因此我想知道这是否是问题之一。

当前Set rg = LoanData.Range("AH2")在一个表中,我已经尝试将该范围内的数据既作为表又作为范围,但是如果数据被跳过,函数中的For循环将被跳过是否在表格中。

Data Set

名为clsCounty的类模块

Public CountyID As Long
Public County As String

名为ReadCounty的函数

Private Function ReadCounty() As Dictionary
    Dim dict As New Dictionary

    Dim rg As Range
    Set rg = LoanData.Range("AH2")

    Dim oCounty As clsCounty, i As Long


    For i = 2 To rg.Rows.Count

        Set oCounty = New clsCounty

        oCounty.CountyID = rg.Cells(i, 1).Value
        oCounty.County = rg.Cells(i, 2).Value

        dict.Add oCounty.CountyID, oCounty
    Next i

    Set ReadCounty = dict


End Function

要写入立即窗口的两个子项目

Private Sub WriteToImmediate(dict As Dictionary)
    Dim key As Variant, oCounty As clsCounty

    For Each key In dict.Keys
        Set oCounty = dict(key)
        With oCounty
            Debug.Print .CountyID, .County
        End With
    Next key

End Sub

Sub Main()
    Dim dict As Dictionary

    Set dict = ReadCounty

    WriteToImmediate dict

End Sub

2 个答案:

答案 0 :(得分:5)

您已将范围声明为Set rg = LoanData.Range("AH2"),然后在循环中使用For i = 2 To rg.Rows.Countrg.Rows.Count将为1,因为您的范围内只有1个单元格。这早于For循环(2)的起始值,因此它不会做任何事情。

For i = 2 to 1

声明完整范围的rg变量。我会猜测类似的东西

With LoanData
    Set rg = .Range(.Cells(1,"AH"), .Cells(.Cells(.Rows.Count, "AH").End(xlUp).Row, "AH"))
End With

答案 1 :(得分:1)

问题确实出在Set rg = LoanData.Range("AH2")as mentioned in the other answer的使用上。

不过,为了更简洁一点,您可以考虑使用LastRow函数,该函数将columnToCheckwsName作为参数:

Public Function LastRow(wsName As String, Optional columnToCheck As Long = 1) As Long

    Dim ws As Worksheet
    Set ws = Worksheets(wsName)
    LastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row

End Function

在代码中,它看起来像这样:

Private Function ReadCounty() As Dictionary

    Dim dict As New Dictionary
    Dim oCounty As clsCounty, i As Long

    'For i = 2 To LastRow("LoanData", 34)
    For i = 2 To LastRow(LoanData.Name, Range("AH1").Column) 
        Set oCounty = New clsCounty
        oCounty.CountyID = LoanData.Cells(i, "AH").Value
        oCounty.County = LoanData.Cells(i, "AI").Value
        dict.Add oCounty.CountyID, oCounty
    Next i

    Set ReadCounty = dict

End Function