[英]How create new sheets with specific names and copy specific values into new sheets
I have an excel file with a list of names(names.xlsm), I want to create another new excel file(separate.xlsx) with different sheets.我有一个包含名称列表(names.xlsm)的 excel 文件,我想用不同的工作表创建另一个新的 excel 文件(separate.xlsx)。 The name of each sheet in separate.xlsx is a name in names.xlsx and the first cell of each sheet is the same name value.在separate.xlsx 中每张表的名称是names.xlsx 中的名称,并且每张表的第一个单元格是相同的名称值。
'''VBA '''VBA
Sub copy_name()
Dim MyCell As Range, MyRange As Range, ws As Worksheet
Dim mybook As Workbook
Set mybook = Workbooks("names.xlsm")
Set MyRange = mybook.Sheets("names").Range("A2:A6") 'eg. five names'
Dim target As Workbook
Set target = Workbooks("separate.xlsx")
i = 1
For Each MyCell In MyRange
Set ws = target.Worksheets.Add(After:=Worksheets(Worksheets.Count)) ' create new worksheet in target file
ws.Name = MyCell.Value ' renames the new worksheet
target.Sheets(MyCell.Value).Cells(1, 1) = MyCell 'copy the value of Mycell to target sheets
i = i + 1
Next
Set mybook = Nothing
Set target = Nothing
End Sub
''' Here is my code. ''' 这是我的代码。 It keeps showing errors and I do not know how to debug.它一直显示错误,我不知道如何调试。
names.xlsm
do not exist in separate.xlsx
.我假设与 names.xlsm 同名的工作names.xlsm
在separate.xlsx
不存在。 If it does then you will have to handle that separately.如果是这样,那么您将不得不单独处理。Is this what you are trying?这是你正在尝试的吗?
Option Explicit
Sub Sample()
Dim wbNames As Workbook, wbSep As Workbook
Dim rng As Range, aCell As Range
Set wbNames = Workbooks("names.xlsm")
Set wbSep = Workbooks("separate.xlsx")
Set rng = wbNames.Sheets("Names").Range("A2:A6")
For Each aCell In rng
With wbSep
.Sheets.Add(After:=.Worksheets(.Worksheets.Count)).Name = aCell.Value
.Worksheets(aCell.Value).Cells(1, 1).Value = aCell.Value
End With
Next
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.