Excel VBA – 编写数组的更有效的方法

我成功地在excel VBA中构build了一个工具,它可以从SAP的CJ74报告中获取数据,并将其合并,并将其迁移到我们在项目办公室工作中使用的金融工具中。

第二个代码使用数组来拉取数据并将其转换为列,这段代码可以正常工作,但是我知道如果编写正确的话,它可以执行得更好。 目前的代码如下,我会欢迎build议,以获得此代码在一行工作。

Sub Array() Dim DateStore As Variant Dim actualcolumnsource As Long, lngcnt as long lngCnt = 0 actualcolumnsource = SourceSheet.Cells(5, Columns.Count).End(xlToRight).row ReDim DateStore(0 To actualcolumnsource) For lngCnt = LBound(DateStore, 1) To UBound(DateStore, 1) If lngCnt = 0 Then DateStore(lngCnt) = SourceSheet.Cells(5, lngCnt + 1).Value Else DateStore(lngCnt) = SourceSheet.Cells(5, lngCnt).Value End If Next lngCnt dumpsheet.Range("E2").Resize((UBound(DateStore) - LBound(DateStore)) + 1, 1).Value = _ Application.Transpose(DateStore) lngCnt = 0 Erase DateStore ReDim DateStore(0 To actualcolumnsource) For lngCnt = LBound(DateStore, 1) To UBound(DateStore, 1) If lngCnt = 0 Then DateStore(lngCnt) = SourceSheet.Cells(5, lngCnt + 1).Column Else DateStore(lngCnt) = SourceSheet.Cells(5, lngCnt).Column End If Next lngCnt dumpsheet.Range("F2").Resize((UBound(DateStore) - LBound(DateStore)) + 1, 1).Value = _ Application.Transpose(DateStore) lngCnt = 0 Erase DateStore ReDim DateStore(0 To actualcolumntarget) For lngCnt = LBound(DateStore, 1) To UBound(DateStore, 1) If lngCnt = 0 Then DateStore(lngCnt) = TargetSheet.Cells(5, lngCnt + 1).Value Else DateStore(lngCnt) = TargetSheet.Cells(5, lngCnt).Value End If Next lngCnt dumpsheet.Range("G2").Resize((UBound(DateStore) - LBound(DateStore)) + 1, 1).Value = _ Application.Transpose(DateStore) lngCnt = 0 Erase DateStore ReDim DateStore(0 To actualcolumntarget) For lngCnt = LBound(DateStore, 1) To UBound(DateStore, 1) If lngCnt = 0 Then DateStore(lngCnt) = TargetSheet.Cells(5, lngCnt + 1).Column Else DateStore(lngCnt) = TargetSheet.Cells(5, lngCnt).Column End If Next lngCnt dumpsheet.Range("H2").Resize((UBound(DateStore) - LBound(DateStore)) + 1, 1).Value = _ Application.Transpose(DateStore) lngCnt = 0 Erase DateStore End Sub 

放弃一维数组并使用二维数组。
这也将消除使用Application.Transpose有其局限性。
考虑下面:(假设你已经得到了实际的actualcolumnsourcevariables)

 ReDim DateStore(1 To actualcolumntarget, 0 To 3) ' explicit array dimensioning For lngcnt = LBound(DateStore, 1) To Ubound(DateStore, 1) Datestore(lngcnt, 0) = SourceSheet.Cells(5, lngCnt).Value2 Datestore(lngcnt, 1) = SourceSheet.Cells(5, lngCnt).Column Datestore(lngcnt, 2) = TargetSheet.Cells(5, lngCnt).Value2 Datestore(lngcnt, 3) = TargetSheet.Cells(5, lngCnt).Column Next dumpsheet.Range("E2:H" & actualcolumntarget + 1) = DateStore 

数组已经明确标注,因此不需要If Statement
另外,写入数组A5的值两次。
最后一行需要+1 ,因为你从第二行开始。
另外,我使用了Value2 ,它比Value属性更快。