【问题标题】:VBA testing values in arrays数组中的 VBA 测试值
【发布时间】:2022-01-05 14:45:58
【问题描述】:

我正在尝试在 VBA 中编写我的第一个更扩展的宏,但在测试数组 1 中的值是否也在数组 2 中时遇到了问题。下面是我的带有 cmets 的代码。我希望有人能帮我解决这个问题,因为它让我发疯:-) 提前谢谢你!

Sub PullingTrxData()

Dim TrxArray As Variant
Dim InvArray As Variant
Dim emailColumn As Range
Dim wsTrx As Worksheet
Dim wsInvoices As Worksheet
Dim trxRange As Range
Dim LastRow As Long
Dim i As Long
Dim j As Long

'setting sheets as variables
Set wsTrx = ThisWorkbook.Worksheets("Transactions")
Set wsInvoices = ThisWorkbook.Worksheets("Invoices Summary")

'finding last non empty row number in column c - email Invoices worksheet
LastRow = wsInvoices.Cells(wsInvoices.Rows.Count, "C").End(xlUp).Row

wsInvoices.Activate
'setting range of all emails already in invoices
If wsInvoices.Range("C3") <> "" Then
    Set emailColumn = wsInvoices.Range("C2", Range("C2").End(xlDown))
    Else: Set emailColumn = wsInvoices.Range("C2")
End If

'loading emails already on invoices sheet into an array
InvArray = emailColumn.Value

'setting range of all transactions  -why do I have to activate wsTrx for it to work?
wsTrx.Activate
Set trxRange = wsTrx.Range("A2", Range("A1").End(xlToRight).End(xlDown))

'loading transactions into array
TrxArray = trxRange.Value

'looping through array and checking if the email address from TransactionsList is already listed on Invoices Summary

For i = LBound(TrxArray, 1) To UBound(TrxArray, 1)

    For j = LBound(InvArray) To UBound(InvArray)
    'testing if email in TrxArray(i,1) already in InvArray(j) if yes then next else add to first empty cell in column C on Invoices summary sheet
        If TrxArray(i, 1) = InvArray(j) Then
        Next j
        Else: ThisWorkbook.Worksheets("Invoices Summary").Range("C" & LastRow).Offset(1, 0).Value = InvArray(j)
        End If
    Next j

Next i

End Sub

【问题讨论】:

  • "为什么我必须激活 wsTrx 才能工作?"因为在wsTrx.Range("A2", Range("A1").End(xlToRight).End(xlDown)) 中,Range("A1") 不符合工作表,因此默认为活动表。使用wsTrx.Range("A1")。同样适用于wsInvoices.Range("C2", Range("C2").End(xlDown))

标签: arrays excel vba


【解决方案1】:

一个数组中的匹配值

您可以使用Application.Match 而不是两个循环:

Dim Trx1Array As Variant: Trx1Array = trxRange.Columns(1).Value

For i = 1 To UBound(InvArray, 1)
    If IsError(Application.Match(InvArray(i, 1), Trx1Array, 0)) Then ' not found
        ThisWorkbook.Worksheets("Invoices Summary").Range("C" & LastRow) _
            .Offset(1, 0).Value = InvArray(i)
    'Else ' found (in Trx1Array)
    End If
Next i

【讨论】:

  • 感谢您的提示!我不得不稍微调整一下,但它终于奏效了!
  • 不客气。我忘了提到Application.Match 在范围上比在数组上快几倍。因此,更有效的解决方案是使用Dim Trx As Range: Set Trx = trxRange.Columns(1) 并使用Trx(范围)而不是Trx1Array
猜你喜欢
  • 2015-02-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-12
  • 1970-01-01
  • 2021-01-14
  • 2019-03-13
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多