我正在研究一个VBA代码,这将允许我日常查看交易头寸的变化。我对VBA编程相当陌生,希望对我写的代码有所反馈(并在此处复制各种帖子)。VBA比较Excel中的行/列
我有3张纸,其中一张是今天的交易(表单1),一张是昨天的交易(表单2)和一张表单,应该突出显示从“第n天”到“第n天”(表单3)的变化。在“A”栏中,我具有对于每笔交易(ID1,ID2等)唯一的交易ID,从列“B”到“AA”,我有诸如日期,值,文本等数据。
In在“更改”表(表3)中,我想在栏“A”中有一条评论,说明交易是“新”,“已删除/已成熟”还是“已更改”。如果一笔交易改变了,我想看看哪些单元格通过显示值前后发生了变化。
我的主要问题是我的代码和性能出错,例如有时我会在电子表格中使用超过500行x 30列。
当我从我的交易系统下载数据到excel时,我有时会有没有内容的单元格,我希望我的代码考虑到这一点。我不认为我现在的代码以一种好的方式做到了这一点。
任何建议/意见将不胜感激!你可以这样做
Sub CompData()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim ws1LRow As Long, ws2LRow As Long
Dim i As Long, j As Long
Dim ws1LCol As Long, ws2LCol As Long
Dim Cell1 As Range, Cell2 As Range
Dim SearchString As String
Dim MatchFound As Boolean
Dim n As Integer
Dim NewDeal As String, MatDeal As String, ChangedDeal As String
NewDeal = "New deal"
MatDeal = "Matured/deleted deal"
ChangedDeal = "Changed deal"
Set ws1 = Sheets("sheet1")
With ws1
ws1LRow = .Range("A" & .Rows.Count).End(xlUp).Row
ws1LCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
End With
Set ws2 = Sheets("sheet2")
With ws2
ws2LRow = .Range("A" & .Rows.Count).End(xlUp).Row
ws2LCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
End With
Set ws3 = Sheets("sheet3")
With ws3
Cells.Clear
End With
n = 1
For i = 1 To ws1LRow
SearchString = ws1.Range("A" & i).Value
Set Cell1 = ws2.Columns(1).Find(What:=SearchString, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not Cell1 Is Nothing Then
Set Cell2 = Cell1
MatchFound = True
For j = 1 To ws1LCol
If ws1.Cells(i, j).Value <> ws2.Cells(Cell1.Row, j).Value Then
MatchFound = False
Exit For
End If
Next
If MatchFound = False Then
ws3.Cells(n, 2).Value = ws1.Cells(i, 1).Value
ws3.Cells(n, j + 1).Value = ws1.Cells(i, j).Value
ws3.Cells(n, ws2LCol + 2).Value = ws2.Cells(i, 1).Value
ws3.Cells(n, ws2LCol + j + 1).Value = ws2.Cells(i, j).Value
ws3.Cells(n, 1).Value = ChangedDeal
n = n + 1
End If
Else:
ws3.Cells(n, 2).Value = ws1.Cells(i, 1).Value
ws3.Cells(n, 1).Value = NewDeal
n = n + 1
End If
Next
ws2.Select
For i = 1 To ws2LRow
SearchString = ws2.Range("A" & i).Value
Set Cell2 = ws1.Columns(1).Find(What:=SearchString, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Cell2 Is Nothing Then
ws3.Cells(n, 2).Value = ws2.Cells(i, 1).Value
ws3.Cells(n, 1).Value = MatDeal
n = n + 1
End If
Next
ws3.Select
End Sub