我是vba编码的新手,我需要它来处理17520行数据的工作表。我需要复制和粘贴12次,每次有1460行数据到另一个工作表运行求解器,然后将解算器的结果粘贴回工作表中。我用相同的命令写了12次vba代码(如下所示只是2次)。现在我正在考虑使用循环方法来总结这个长代码,我不知道如何开始。有人可以帮我这个吗?
Sub RunModel()
Dim Data As Worksheet
Dim Model As Worksheet
Set Data = Sheets("Customer 1 (A)")
Set Model = Sheets("Sheet 1")
'1st month
'Copy Data
Data.Range("D8:E1467").Copy Model.Range("D8")
Data.Range("L8:L1467").Copy Model.Range("L8")
Data.Range("I7").Copy
Model.Range("I7").PasteSpecial (xlPasteValues)
'Run OpenSolver
Result = RunOpenSolver(False, True)
'Paste result and datas back to Data
Model.Range("N4").Copy
Data.Range("Q7").PasteSpecial (xlPasteValues)
Model.Range("F8:O1467").Copy Data.Range("F8")
'2nd month
'Copy Data
Data.Range("D1468:E2927").Copy Model.Range("D8")
Data.Range("L1468:L2927").Copy Model.Range("L8")
Data.Range("I1467").Copy
Model.Range("I7").PasteSpecial (xlPasteValues)
'Run OpenSolver
Result = RunOpenSolver(False, True)
'Paste result and datas back to Data
Model.Range("N4").Copy
Data.Range("Q8").PasteSpecial (xlPasteValues)
Model.Range("F8:O1467").Copy Data.Range("F1468")
答案 0 :(得分:2)
Jeeped回答的另一种选择。相同的概念(使用For .. Next
)但代码略有不同。
dim i as long
dim rowOffset as long
const rowLength as Long = 1460 ' magic number
const startRow as long = 8 ' magic number
for i= 1 to 12 ' note, standard step of 1
rowOffset = (i - 1) * rowLength + startRow
Data.Range(Data.Cells(4, rowOffset), Data.Cells(4,rowOffset + rowLength -1)).Copy Model.Range("D8")
Data.Range(Data.Cells(12, rowOffset), Data.Cells(12,rowOffset + rowLength -1).Copy Model.Range("L8") 'Why copy over same cell?
rowOffset = (i - 1) * rowLength
Model.Range("I7") = Data.Range("I7").offset(rowOffset, 0).value
'Run OpenSolver
Result = RunOpenSolver(False, True)
'Paste result and datas back to Data
Data.Range("Q7").offset(i, 0) = Model.Range("N4").value
rowOffset = (i - 1) * rowLength
Model.Range("F8:O1467").Copy Data.Range("F8").offset(rowOffset, 0)
next i
答案 1 :(得分:0)
使用For ... Next使用非默认步骤。
dim i as long
for i=1 to 17520 step 1460
Data.Range("D8:E1467").offset(i-1, 0).Copy Model.Range("D8")
Data.Range("L8:L1467").offset(i-1, 0).Copy Model.Range("L8")
Model.Range("I7") = Data.Range("I7").offset(i-1, 0).value
'Run OpenSolver
Result = RunOpenSolver(False, True)
'Paste result and datas back to Data
Data.Range("Q7").offset(i\1460, 0) = Model.Range("N4").value
Model.Range("F8:O1467").Copy Data.Range("F8").offset(i-1, 0)
next i