2017-04-14 65 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