【发布时间】: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))