[英]How to write a VBA code that will loop through a fixed range and populate each row of that range N times (with numbering) in another sheet?
I'm fairly new to using For Loops and am stuck on getting this code to work - would appreciate any help.我对使用 For Loops 还很陌生,并且一直坚持让这段代码正常工作 - 非常感谢任何帮助。
I am trying to write a code that will take a fixed range with two columns (Site and Family combination) and populate it onto another sheet, along with numbering months 1 to 12 in an additional column.我正在尝试编写一个代码,该代码将采用两列(站点和家庭组合)的固定范围并将其填充到另一张纸上,并在附加列中对 1 到 12 个月进行编号。
The source data is in the sheet named LM and looks like this:源数据位于名为LM的工作表中,如下所示:
Site Family
Site1 Family1
Site2 Family2
[...]
The outcome should populate in sheet named MS and look like this:结果应填充在名为MS的工作表中,如下所示:
Site Family Month
Site1 Family1 1
Site1 Family1 2
Site1 Family1 3
Site1 Family1 4
Site1 Family1 5
Site1 Family1 6
Site1 Family1 7
Site1 Family1 8
Site1 Family1 9
Site1 Family1 10
Site1 Family1 11
Site1 Family1 12
Site2 Family2 1
Site2 Family2 2
Site2 Family2 3
Site2 Family2 4
Site2 Family2 5
Site2 Family2 6
Site2 Family2 7
Site2 Family2 8
Site2 Family2 9
Site2 Family2 10
Site2 Family2 11
Site2 Family2 12
[...]
Here is the code I have:这是我的代码:
Sub UpdateManualStaging()
Dim MS As Worksheet, LM As Worksheet
Dim SiteLM, FamilyLM, SiteMS, FamilyMS
Dim i As Long, k As Long, l As Long, m As Long
Set LM = Sheets("Lookup & Mapping")
Set MS = Sheets("Manual Staging")
With LM
i = .Cells(.rows.count, 23).End(xlUp).Row
End With
For k = 5 To i
SiteLM = LM.Cells(k, 23).Value
FamilyLM = LM.Cells(k, 24).Value
For l = 5 To 17 Step 11
SiteMS = MS.Cells(l, 3).Value
FamilyMS = MS.Cells(l, 4).Value
MS.Cells(l, 3).Value = LM.Cells(k, 23).Value
MS.Cells(l, 4).Value = LM.Cells(k, 24).Value
For m = 1 To 12
MS.Cells(l, 5).Value = m
Next m
Next l
Next k
End Sub
Maybe something like this?也许是这样的?
Sub test()
Set LM = Sheets("Lookup & Mapping")
Set MS = Sheets("Manual Staging")
Set strt = LM.Range("w2:x2") 'assumed that the data in sheet LM starts from cell w2 (site) and x2 (family).
Do
Set f = MS.Range("C" & Rows.Count).End(xlUp).Offset(1, 0) 'assumed that the result in sheet MS starts from cell c2 (site), d2 (family), e2 (month).
f.Offset(0, 2).Value = 1
f.Resize(12, 2).Value = strt.Value
f.Offset(0, 2).AutoFill Destination:=f.Offset(0, 2).Resize(12), Type:=xlFillSeries
Set strt = strt.Offset(1, 0)
Loop Until Application.CountA(strt) = 0
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.