我有一個Excel VBA代碼,它可以根據一組標準循環訪問一個範圍,從一行復制特定的單元格。下面的代碼只是發現,我想知道是否有一個更清潔的方式來構建它?清潔的方式來寫入副本和過去的循環代碼?
Dim sh1 As Worksheet, sh2 As Worksheet
Dim LastRow As Long, i As Long, j As Long
With ThisWorkbook
Set sh2 = .Sheets.Add(After:=.Sheets(.Sheets.Count))
sh2.Name = "Upload"
sh2.Range("A1").Value = "Date"
sh2.Range("B1").Value = "Ledger Acct"
sh2.Range("C1").Value = "Department"
sh2.Range("D1").Value = "Cost Center"
sh2.Range("E1").Value = "Purpose"
sh2.Range("F1").Value = "Account Name"
sh2.Range("G1").Value = "Transaction Text"
sh2.Range("H1").Value = "Line Amount"
sh2.Range("I1").Value = "Currency"
End With
Set sh1 = Sheets("Remaining for Uploads")
'This will find the last used row in a column A on sh1'
With sh1
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
'First row number where the values will be pasted in Upload'
With sh2
j = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
For i = 2 To LastRow
With sh1
If Not (IsEmpty(.Cells(i, 7))) And Not (IsEmpty(.Cells(i, 8))) And Not (IsEmpty(.Cells(i, 9))) And Not (IsEmpty(.Cells(i, 10))) Then
.Cells(i, 7).Copy
sh2.Range("B" & j).PasteSpecial xlPasteValues
.Cells(i, 8).Copy
sh2.Range("C" & j).PasteSpecial xlPasteValues
.Cells(i, 9).Copy
sh2.Range("D" & j).PasteSpecial xlPasteValues
.Cells(i, 10).Copy
sh2.Range("E" & j).PasteSpecial xlPasteValues
.Cells(i, 13).Copy
sh2.Range("H" & j).PasteSpecial xlPasteValues
j = j + 1
End If
End With
Next i
請勿實際複製/粘貼。您可以直接將值分配給單元格。你的第一個將是'sh2.Range(「B」&j)= .Cells(i,7)'。我也會把你的'With..EndWith'移到循環的外面。它不需要在裏面,我相信你正在拿走它的一些好處。 – Kyle