簡體   English   中英

何時評估 VBA 中的條件?

[英]When is for condition in VBA evaluated?

我想問一下何時評估 VBA(可能是多種語言)中的條件。 我正在嘗試編寫從 excel 表中的兩個表創建兩個字典的代碼。 第一個字典鍵是單詞的英文名稱,值是 class 對象(實例)和其他語言的單詞。

第二個字典鍵是英文月份名稱,值是帶有月份名稱和索引的 class 對象(實例)。

因為第一個字典可以包含隨機單詞而不僅僅是幾個月我想從第一個字典中刪除隨機鍵:值對。

我不明白為什么我必須輸入注釋的代碼行來糾正工作 function? 為什么條件可以高於 dictionary.Count 以及何時評估。

謝謝你的回答。

Sub makro()
    Dim list_dict As Object

    Set list_dict = get_list_dict()

    Set list_dict = Nothing
End Sub

Function get_list_dict() As Object

Dim list_dict As Object
Dim months_dict As Object
Dim list_object As List
Dim months_object As Months
Dim object_index As Integer
Dim row_number As Integer

Set list_dict = CreateObject("Scripting.Dictionary")
Set months_dict = CreateObject("Scripting.Dictionary")

For row_number = 2 To ThisWorkbook.Sheets("List").Cells(2, "A").CurrentRegion.Rows.Count
    Set list_object = New List
    
    list_object.english = ThisWorkbook.Sheets("List").Cells(row_number, "A").Value
    list_object.slovak = ThisWorkbook.Sheets("List").Cells(row_number, "B").Value
    list_object.czech = ThisWorkbook.Sheets("List").Cells(row_number, "C").Value
    
    list_dict.Add list_object.english, list_object
Next row_number

For row_number = 2 To ThisWorkbook.Sheets("Months").Cells(2, "A").CurrentRegion.Rows.Count
    Set months_object = New Months
    
    months_object.name = ThisWorkbook.Sheets("Months").Cells(row_number, "B").Value
    months_object.index = ThisWorkbook.Sheets("Months").Cells(row_number, "A").Value
    
    months_dict.Add months_object.name, months_object.index
Next row_number

For object_index = 0 To list_dict.Count - 1
    If Not months_dict.Exists(list_dict.Keys()(object_index)) Then

        list_dict.Remove list_dict.Keys()(object_index)
        
        ' this one I understand 
        object_index = object_index - 1
        
        ' this one not 
        If object_index = list_dict.Count - 1 Then Exit For
        
    End If
    
Next object_index

Set get_list_dict = list_dict

Set list_dict = Nothing
End Function

列表 class:

Public english As String
Public slovak As String
Public czech As String

月份 class:

Public index As Integer
Public name As String

在此處輸入圖像描述

在循環期間刪除項目時,最好向后工作,因此不需要更正刪除的項目。 生成的代碼更容易推理。

For object_index = list_dict.Count - 1 to 0 Step - 1
    If Not months_dict.Exists(list_dict.Keys()(object_index)) Then
        list_dict.Remove list_dict.Keys()(object_index)
    End If
Next object_index

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM