遍历名称列表,并且如果名称存在于选择之后,则从姓氏开始

问题描述 投票:0回答:1

抱歉,这是我第一次使用Excel VBA,所以请原谅我缺乏知识!

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS85SGw4Ni5qcGcifQ==” alt =“我的示例屏幕截图”>

因此,我有一个(当前)3个名称的列表,这些列表以Excel中的重复顺序分配给A列中的日期。

当前,我的VBA代码允许它以重复的模式用名称填充所选单元格(这部分很好),但是我需要帮助的有两部分。

1-使用当前代码,一旦到达名称的底部,它将检查将在该列表结尾的空白框,并按照指示从顶部开始,但是它将空白单元格放在第一位(请参见屏幕截图)。如何在不先添加空白单元格的情况下放置名字?

2-我希望能够(一旦完成)选择需要填写日期的整个D列,并::

-选中最低的非空白框

-匹配以列出并设置相对于此名称它继续名称顺序从最后一个人已分配

这是我现在拥有的代码:

Sub EXAMPLE()
Dim count As Integer
count = 0
For Each c In Selection
    c.Value = Range("X1").Offset(count, 0).Value
    If c.Value = "" Then count = -1 And c.Value = Range("x1").Offset(count, 0).Value
    count = count + 1
Next c
End Sub

对不起,我知道那很长,希望这是有道理的。

excel vba loops
1个回答
0
投票

我认为值得阅读有关数组的内容,因为此任务非常适合它们的使用。最好的选择是将名称读入数组,然后构建一个重复数组,其维度等于日期列中的行数(或选择项,或者您想要定义输出范围的大小)。] >

代码看起来像这样:

Dim v As Variant
Dim people() As Variant, output() As Variant
Dim rowCount As Long, i As Long, j As Long
Dim endRange As Range

'Read the list of names into an array.
'This just takes all data in column "X" -> amend as desired
With Sheet1
    Set endRange = .Cells(.Rows.Count, "X").End(xlUp)
    v = .Range(.Cells(1, "X"), endRange).Value
End With

'Sense check on the names data.
If IsEmpty(v) Then
    MsgBox "No names in Column ""X"""
    Exit Sub
End If

If Not IsArray(v) Then
    ReDim people(1 To 1, 1 To 1)
    people(1, 1) = v
Else
    people = v
End If

'Acquire the number of rows for repeating list of names.
'This just takes all data in column "A" -> amend as desired
With Sheet1
    Set endRange = .Cells(.Rows.Count, "A").End(xlUp)
    rowCount = .Range(.Cells(3, "A"), endRange).Rows.Count
End With

'Sense check date data.
If endRange.Row < 3 Then
    MsgBox "No dates in Column ""A"""
    Exit Sub
End If

'Make a recurring array.
ReDim output(1 To rowCount, 1 To 1)
i = 1
Do While i <= rowCount
    For j = 1 To UBound(people, 1)
        output(i, 1) = people(j, 1)
        i = i + 1
        If i > rowCount Then Exit Do
    Next
Loop

'Write the output to column "D"
Sheet1.Range("D3").Resize(UBound(output, 1)).Value = output
© www.soinside.com 2019 - 2024. All rights reserved.