首页 > 解决方案 > VBA Excel 宏条件中的 For 循环未按预期工作

问题描述

我正在尝试运行下面的 VBA 代码并且它正在运行。但是在某些情况下结果与预期不符例如我有一列值,脚本查看整列选择最小值并将 +1 添加到输出。但是有时它会跳过这个原始列中的一些小值并取更高的值,我不明白它为什么这样做

我在此处附上了 excel 宏工作簿: https ://drive.google.com/open?id=1IAHalTjWoTqRT10mgF6bu5l4VB1HgCfv

输出工作表被称为:“循环”宏可以从工作表运行:“指令”

Option Explicit


Sub Loop_Forecast()


Dim Onglet_Loop As String
Dim First_Ligne, First_Col_Fct, Col_SKU, Col_Inventory, Col_Monthly_Demand, Col_Coverage As Integer
Dim i, Last_ligne, Ligne_Smallest As Long
Dim Qty_Fct_Origin, Qty_Fct_Remain, Compteur, Smallest_Coverage As Variant


'Fige l'écran pendant la suppression des lignes
Application.ScreenUpdating = False


Onglet_Loop = "Loop"
Worksheets(Onglet_Loop).Activate

First_Ligne = 3
Last_ligne = Cells(First_Ligne, 1).End(xlDown).Row

Qty_Fct_Origin = Cells(1, 2).Value
Col_SKU = 1
Col_Inventory = 2
Col_Monthly_Demand = 3
Col_Coverage = 4
First_Col_Fct = 5

Compteur = 0

Do While Compteur < Qty_Fct_Origin

        Compteur = Compteur + 1
        Smallest_Coverage = Cells(First_Ligne, Col_Coverage).Value
        Ligne_Smallest = First_Ligne

    For i = First_Ligne + 1 To Last_ligne
        If Cells(i, Col_Coverage).Value < Smallest_Coverage Then
            Smallest_Coverage = Cells(i, Col_Coverage).Value
            Ligne_Smallest = i
        End If
    Next i

        Cells(Ligne_Smallest, First_Col_Fct).Value = Cells(Ligne_Smallest, First_Col_Fct).Value + 1
Loop


'Faire plein de choses qui affectent le contenu des cellules
Application.ScreenUpdating = True


End Sub

我附上了我收到的输出的图像。可以看出,它正在跳过一些较小的值,即 4 应该是优先级,然后跳转到 5 在此处输入图像描述

标签: excelvba

解决方案


推荐阅读