【问题标题】:how to change column after n rows while inserting values from array to excel cell VBA如何在将值从数组插入到excel单元格VBA时更改n行后的列
【发布时间】:2021-04-21 20:19:29
【问题描述】:

您能否指导如何将数组值放在多列中,例如第一列中的前四个值,第二列中的 5 个值,第二列中可能有 2 个......等等。我试过做while循环和for循环,但结果都不理想—————————-

    Sub PickNamesAtRandom()
Dim HowMany As Long
Dim NoOfNames As Long
Dim RandomColumn As Integer
Dim RandomRow As Integer
Dim Names() As String ‘Array to store randomly selected names
Dim i As Byte
Dim CellsOutRow As Integer
Dim CellsOutColumn As Integer ‘Variable to be used when entering names onto worksheet
Dim ArI As Byte ‘Variable to increment through array indexes

Application.ScreenUpdating = False
HowMany = WorksheetFunction.Sum(Sheets(“test”).Range(“A2:E2”))
CellsOutRow = 3
CellsOutColumn = 1
ReDim Names(1 To HowMany) ‘Set the array size to how many names required
NoOfNames = Application.CountA(Sheets(“sheet1”).Range(“D4:L45”)) ‘ Find how many names in the list
i = 1
Do While i <= HowMany
RandomNo:
RandomRow = Application.RandBetween(1, 45)
RandomColumn = Application.RandBetween(1, 15)
'Check to see if the name has already been picked
For ArI = LBound(Names) To UBound(Names)
If Names(ArI) = Sheets("sheet1").Cells(RandomRow, RandomColumn).Value Then
GoTo RandomNo
End If
Next ArI
Names(i) = Sheets("sheet1").Cells(RandomRow, RandomColumn).Value ' Assign random name to the array
i = i + 1
Loop
Dim RequiredRows As Integer
RequiredRow = 2
'Loop through the array and enter names onto the worksheet
For ArI = LBound(Names) To UBound(Names)

Do
Cells(CellsOutRow, CellsOutColumn) = Names(ArI)
CellsOutRow = CellsOutRow + 1
Loop While CellsOutRow < Cells(RequiredRow, CellsOutColumn).Value
CellsOutColumn = CellsOutColumn + 1
Next ArI
Application.ScreenUpdating = True
End Sub

【问题讨论】:

  • 为了我们和您自己的利益,请在发布时缩进代码,否则很难说出发生了什么。

标签: excel vba loops


【解决方案1】:
Option Explicit

Sub WriteValues(ByVal values As Collection)

    Dim row As Long
    Dim col As Long
    Dim val As Variant
    
    row = 1
    
    For Each val In values
    
        Select Case row
    
            ' first four values in first column
            Case Is <= 4
                col = 1
    
            ' than 5 values in second column,
            Case Is <= 9
                col = 2
    
            ' and than may be 2 in second column...
            Case Is <= 11
                col = 2
    
            ' row > 11
            Case Else
                col = 3
    
        End Select
    
        Cells(row, col).Value = val
        
        row = row + 1
    
    Next val

End Sub

【讨论】:

    猜你喜欢
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多