【发布时间】:2020-08-03 15:06:51
【问题描述】:
我编写了以下代码,用于将数据从一个工作簿复制到另一个工作簿中的特定单元格(我认为这是一个挑战,目标文件有月份和下面的相关数据,每个月我都需要将数据复制到当前月份列,这就是为什么使用“最后一列”功能不覆盖历史月份也使其动态地转到没有当前月份数据的最后一列)。即使代码运行良好,我也想对其进行优化以便轻松调试并避免将来出现问题;本年度发生了变化。 你有什么想法可以让这段代码变得更好?
代码
Dim x, LastRow, LastColumn, workfile, sourcefile As String
sourcefile = ActiveWorkbook.Name
workfile = ThisWorkbook.Name
LastRow = Range("A" & Rows.Count).End(xlUp).Row
For x = LastRow To 1 Step -1
If Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 1).Value = "001B" And Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 2).Value = "GBP" Then
Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 8).Copy
Workbooks(workfile).Worksheets("A").Activate
Lastcolumn2 = Workbooks(workfile).Worksheets("A").Cells(28, 21).End(xlToLeft).Column + 1
Workbooks(workfile).Worksheets("A").Cells(28, Lastcolumn2).PasteSpecial xlPasteValues
Else
End If
If Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 1).Value = "001R" And Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 2).Value = "GBP" Then
Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 8).Copy
Workbooks(workfile).Worksheets("A").Activate
Lastcolumn3 = Workbooks(workfile).Worksheets("A").Cells(29, 21).End(xlToLeft).Column + 1
Workbooks(workfile).Worksheets("A").Cells(29, Lastcolumn3).PasteSpecial xlPasteValues
Else
End If
If Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 1).Value = "001B" And Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 2).Value = "EUR" Then
Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 8).Copy
Workbooks(workfile).Worksheets("A").Activate
Lastcolumn4 = Workbooks(workfile).Worksheets("A").Cells(35, 21).End(xlToLeft).Column + 1
Workbooks(workfile).Worksheets("A").Cells(35, Lastcolumn4).PasteSpecial xlPasteValues
Else
End If
If Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 1).Value = "001R" And Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 2).Value = "EUR" Then
Workbooks(sourcefile).Worksheets("exchangedownload").Cells(x, 8).Copy
Workbooks(workfile).Worksheets("A").Activate
Lastcolumn5 = Workbooks(workfile).Worksheets("A").Cells(36, 21).End(xlToLeft).Column + 1
Workbooks(workfile).Worksheets("A").Cells(36, Lastcolumn5).PasteSpecial xlPasteValues
Else
End If
Next
【问题讨论】:
-
这个问题可能更适合Code Review。
标签: excel vba loops if-statement copy-paste