VBA 当有多个满足条件的值时,for循环只返回一个值

VBA for loop only returning one value when there are more that meet the criteria

我正在尝试将股票交易从交易工作簿转移到另一本具有我想要的格式的工作簿。我希望能够更改代码顶部的客户名称和股票,以便更轻松地为多人 运行。问题是,当我 运行 这只在我的格式化工作表中 returns 一个日期时,我可以看到交易簿中给定代码有 3 笔不同日期的股票交易。似乎 FOR 函数没有遍历交易簿中的所有行,但我不确定为什么

Sub SortTransactionData()


Dim wb As Workbook
Dim ws As Worksheet

Set wb = Workbooks("Allen Smith Transactions.xlsx")
Set ws = wb.Sheets("Sheet1")

Dim wb1 As Workbook 
Dim ws1 As Worksheet

Set wb1 = Workbooks("Allen Smith HI.xlsm")
Set ws1 = wb1.Sheets("MO")

Dim ticker As String
ticker = ws1.Range("A2")

Dim a As Integer
a = ws.Cells(Rows.Count, 6).End(xlUp).Row

Dim b As Integer
b = Application.WorksheetFunction.CountIf(ws1.Range("B1:B7"), "*")

For i = 2 To a
    'copy date for stock transaction'
    If ws.Cells(i, 6).Value = ticker Then
    ws1.Cells(b + 1, 2).Value = ws.Cells(i, 1)
    End If

Next
End Sub

如评论中所述,问题是单元格 ws1.Cells(b + 1, 2) 永远不会更改,因此您在循环过程中不断覆盖旧值

更改代码以增加索引,b,每次循环:

For i = 2 To a
    'copy date for stock transaction'
    If ws.Cells(i, 6).Value = ticker Then
        ws1.Cells(b + 1, 2).Value = ws.Cells(i, 1)
        b = b + 1
    End If
Next i