0

我这里有个问题,我一直在尝试使用 VBA 在一个范围内均匀分布一个已知数字。问题是我需要找到范围内的数字尽可能相等的方式,你可以帮帮我吗?或给出想法?

数据集如下

在此处输入图像描述

已知数字由红色的“TV Comodin”行给出,这是我的尝试:

    Sub Prueba()

  Columns("A:A").Select
    Set Cell = Selection.Find(What:="TV Comodín", After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
    ActiveCell = Cell
    Cell.Select
    
    comodin = ActiveCell.Offset(0, 1).Value2

    Range("A2").Select
    Firstrow = ActiveCell.Row
    Selection.End(xlDown).Select
    Lastrow = ActiveCell.Row

    j = comodin 
While (j > 0)
        For i = 2 To Lastrow
        Range("B2").Select
        Range("B" & i) = Range("B" & i).Value + 1
        If j > 0 Then j = j - 1
        If j = 0 Then Exit For
   
    Next

Wend
          
End Sub

基本上,我的代码找到“TV Comodin”行以获得循环将在其列的每一行中添加 1 乘 1 的次数,

抱歉,我对 VBA 有点陌生,顺便谢谢你。

4

1 回答 1

0

这是一种方法。找到范围内的最小数字:加一。重复,直到你完成了(例如)55 次。

Sub Prueba()
    Dim f As Range, ws As Worksheet, comodin As Long, rng As Range, m, mn
    
    Set ws = ActiveSheet
    
    Set rng = ws.Range("A2", ws.Range("A2").End(xlDown)).Offset(0, 1)
    
    Set f = ws.Columns("A").Find(What:="TV Comodín", LookIn:=xlFormulas, _
                                 LookAt:=xlWhole, MatchCase:=False)
   
    If Not f Is Nothing Then
        rng.Value = ws.Evaluate("=" & rng.Address() & "*1") 'fill empty cells with zeros
        comodin = f.Offset(0, 1).Value
        Do While comodin > 0
            mn = Application.Min(rng)
            If mn >= 100 Then Exit Do ' exit when no values are <100 
            m = Application.Match(mn, rng, 0)
            rng.Cells(m).Value = rng.Cells(m).Value + 1
            comodin = comodin - 1
        Loop
    Else
        MsgBox "not found!"
    End If
End Sub
于 2021-01-08T23:56:39.610 回答