我正在编写一个 VBA 代码,它可以让我看到每天交易头寸的变化。我对 VBA 编程相当陌生,想获得一些关于我编写的代码的反馈(并从这里的各种帖子中复制)。
我有 3 张纸,一张是今天的交易(sheet1),一张是昨天的交易(sheet2),还有一张应该突出从“第 n 天”到“第 n-1 天”的变化(第 3 天)。在“A”列中,我有每个交易唯一的交易 ID(ID1、ID2 等),从“B”列到“AA”,我有日期、值、文本等数据。
在“更改”表(表 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