将数据从工作表复制到模板中

时间:2014-08-28 09:24:22

标签: excel vba

我正在尝试将单元格中的数据从工作表复制到模板中。如果我只尝试从一列复制数据,但是当我尝试从第二列复制数据时,我可以让代码工作。有人可以解释我哪里出错了。感谢

我需要来自A列的数据进入新工作表上的单元格B4,来自b列的数据进入新工作表上的单元格B5,并为每个行创建一个新文件,以便每个人有年假文件。

这有效

Sub create()
Dim wb As Workbook, sh1 As Worksheet, lr As Long, rng As Range
Set sh1 = Sheets("leave entitlement")
lr = sh1.Cells(Rows.Count, "A").End(xlUp).Row
Set rng = sh1.Range("A2:A" & lr)
For Each c In rng
    Sheets("Template").Copy 'Edit sheet name
    Set wb = ActiveWorkbook
    wb.Sheets(1).Range("B4") = c.Value
    wb.SaveAs Filename:="H:\Temporary files\" & c.Value & ".xlsx"
    wb.Close False
Next
End Sub

这不起作用

Sub create()
Dim wb As Workbook, sh1 As Worksheet, lr As Long, rng As Range, rng1 As Range, hr As Long
Set sh1 = Sheets("leave entitlement")
lr = sh1.Cells(Rows.Count, "A").End(xlUp).Row
hr = sh1.Cells(Rows.Count, "B").End(xlUp).Row
Set rng = sh1.Range("A2:A" & lr)
Set rng1 = sh1.Range("B2:B" & hr)
For Each c In rng
    Sheets("Template").Copy 'Edit sheet name
    Set wb = ActiveWorkbook
    wb.Sheets(1).Range("B4") = c.Value
    wb.Sheets(1).Range("B5") = rng1.Value
    wb.SaveAs Filename:="H:\Temporary files\" & c.Value & ".xlsx"
    wb.Close False
Next
End Sub

0 个答案:

没有答案