2017-04-14 64 views
1

我想写一个宏,它将根据其他单元格中的条件打印出数组中的值。我已经获得了宏在数组中打印出一个值,但不是其他值。电子表格如下:打印数组值可变的次数

Column 1 | Column 2 
___________________ 
L1  | 
L1  | 
L2  | 
L3  | 
L1  | 
L5  | 
L1  | 

数组看起来像这样:列表=阵列(“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人的名字,在实际的电子表格,这就是为什么在宏列不我添加了样本数据匹配列这里。

回答

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 
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