我有以下银行对帐代码,其中包括检查sheet1(银行对帐单)D列中的每个单元格,并查看它是否存在于工作表2的M列中。如果它没有通过将其保存到arrOutput。
作为一名新用户,由于无法附加电子表格,因此我找到了第1页和第2页的链接。
Sub abc_3()
Dim i As Long, ii
Dim arrBank As Range
Dim arrAccounting As Range
Dim arrOutput
Dim temp As Variant
' setting bank transaction into range
Set bank = ActiveWorkbook.Sheets("Sheet1").Range("D25:E25" & Cells(Rows.Count, "D").End(xlUp).Row)
' setting accounting transactions into range
Set books = ActiveWorkbook.Sheets("Sheet2").Range("M1:N1" & Cells(Rows.Count, "M").End(xlUp).Row)
'everytime time the program is run arrOutput must be cleared. 3000 is an arbitrary number I chose because there will likely never be a higher number of transactions than this.
ReDim arrOutput(1 To 3000, 1 To 2)
ii = 0
' The main function of the program.. looping through every bank transaction checking if it can be found in accounting transactions,
' if it cannot be found, i.e error is thrown then save the cell to arrOutput because it needs to be flagged for checking.
' if it can be found, then ignore and check next bank transaction.
' Currently, the procedure is supposed to compare only Sheet1 credit transactions with Sheet2 credit transactions, therefore filter only credit transactions.
For Each cell In bank.Cells 'problem here is comparing both Column D and E of Sheet 1 whereas it should be comparing only column D.
If cell <> "" Then 'this is to avoid checking non-credit transactions.
On Error Resume Next
temp = Application.WorksheetFunction.VLookup(cell, books, 2, False)
If Err.Number <> 0 Then
MsgBox "Bank Transaction " & cell & " could not be found in Books Transaction history"
arrOutput(ii, 1) = cell
arrOutput(ii, 2) = ""
ii = ii + 1
End If
End If
Next
'all cells checked then dump arrOutput to range "L4" for reading
Range("l4").Resize(3000, 2) = arrOutput
bank.ClearContents
books.ClearContents
End Sub
问题在于每个小区都有MSG&#34;银行交易&#34; &安培;细胞和细胞&#34;在图书交易历史记录&#34;中找不到。因此,每个单元格都保存到arrOutput并保存到Sheets(&#34; Sheet3&#34;)。范围(&#34; L4&#34;)让我想知道Vlookup是不合作还是我没有设置错误处理程序正确。
期待得到一些帮助..长期坚持这一点。提前谢谢。
答案 0 :(得分:0)
1)您应该对范围进行限定。 2):E25
应为:D
,:N1
应为:M
。 3)使用Option Explicit并使用您声明的变量(您声明了一些变量名,但之后使用其他名称......)。 4)最后,使用Find
代替VLookup
,因为您只想检查值的存在,而不是相应的其他值。
Option Explicit
Sub abc_3()
Dim bank As Range, books As Range, cell As Range
With ActiveWorkbook.Sheets("Sheet1")
Set bank = .Range("D26:D" & .Cells(.Rows.Count, "D").End(xlUp).Row)
End With
With ActiveWorkbook.Sheets("Sheet2")
Set books = .Range("M2:M" & .Cells(.Rows.Count, "M").End(xlUp).Row)
End With
Dim ii As Long, x As Range, arrOutput(1 To 3000, 1 To 2)
For Each cell In bank.Cells
If Trim(cell.Value) <> "" Then
Set x = books.Find(cell.Value, , xlValues, xlWhole)
If x Is Nothing Then
ii = ii + 1
arrOutput(ii, 1) = cell.Value
MsgBox "Bank Transaction " & cell.Value & " could not be found in Books Transaction history"
Else
x.Value = ""
End If
End If
Next
ActiveWorkbook.Sheets("Sheet3").Range("l4").Resize(3000, 2) = arrOutput
End Sub