我正在尝试编写一个宏,它将根据其他单元格中的条件打印出数组中的值。我已经得到了宏来打印出数组中的一个值,而不是其他值。电子表格如下所示:
Column 1 | Column 2
___________________
L1 |
L1 |
L2 |
L3 |
L1 |
L5 |
L1 |
数组看起来像这样:List = Array(“Person1”,“Person2”,“Person3”),我想要做的是打印Person1,Person2等,为L1表示最后L1的每个值值。它应该如下所示。
Column 1 | Column 2
___________________
L1 | Person1
L1 | Person2
L2 |
L3 |
L1 | Person3
L5 |
L1 | Person1
下面的宏部分工作,但它只打印一个人,Person3。任何帮助将不胜感激!
Sub Practice()
Dim i, j, k As Integer
Dim List As Variant
Dim LastRow As Long, CountL As Long
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Sheet1")
List = Array("Person1", "Person2", "Person3")
LastRow = ws.Cells(Rows.Count, "C").End(xlUp).Row - 1
For i = LBound(List) To UBound(List)
For j = 2 To LastRow
If ws.Cells(j, 3).Value = "L1" Then
ws.Cells(j, 4) = List(i)
Else 'Do Nothing
End If
Next j
Next i
End Sub
请注意,“L”值位于C列,实际电子表格中列D中的人员名称,这就是宏中的列与我在此处添加的示例数据中的列不匹配的原因。
答案 0 :(得分:1)
看一下下面的例子:
Sub Practice()
Dim ws As Worksheet
Dim List As Variant
Dim LastRow As Long
Dim i As Integer
Dim j As Integer
Set ws = ThisWorkbook.Sheets("Sheet1")
List = Array("Person1", "Person2", "Person3")
LastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
i = 0
For j = 2 To LastRow
If ws.Cells(j, 3).Value = "L1" Then
ws.Cells(j, 4) = List(i Mod 3)
i = i + 1
End If
Next
End Sub
答案 1 :(得分:0)
您的代码当前正在为列表中的每个值重复其操作,每次迭代都会为每个L1行分配一个值,并覆盖上一次迭代中写入的内容。
您实际上需要保留一个计数器,表明您要在下一个要编写的数组中使用哪个值:
Sub Practice()
'You should declare the type of each variable, or else they will be Variant
'Dim i, j, k As Integer
Dim i As Integer, j As Integer, k As Integer
Dim List As Variant
Dim LastRow As Long, CountL As Long
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Sheet1")
List = Array("Person1", "Person2", "Person3")
'You should fully qualify objects such as Range, Cells and Rows
'LastRow = ws.Cells(Rows.Count, "C").End(xlUp).Row - 1
LastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row '<-- not sure why you subtracted 1
i = LBound(List)
For j = 2 To LastRow
If ws.Cells(j, 3).Value = "L1" Then
ws.Cells(j, 4) = List(i)
i = i + 1
If i > UBound(List) Then
i = LBound(List)
End If
End If
Next j
End Sub