复制后重命名工作表并创建主工作簿

时间:2016-03-21 19:37:50

标签: excel vba excel-vba

下面是用于从源复制工作表然后重命名并放入目标的代码。

我想扩展功能以使用另一个单元格引用来重命名新创建的文件中的工作表名称。 (请注意,每个复制的工作簿只有一个工作表。)然后,在重命名所有工作簿,重命名和工作表重命名后,将目标路径中的所有工作簿合并为一个。

Sub CopyRenameFile()
Dim src As String, dst As String, fl As String, f2 As String
Dim rfl As String
Dim rf2 As String

'Source directory
src = Range("B3")

'Destination directory
dst = Range("D3")

'File name
fl = Range("B6")
f2 = Range("B7")

'Rename file
rfl = Range("D6")
rf2 = Range("D7")

On Error Resume Next
    FileCopy src & "\" & fl, dst & "\" & rfl
    FileCopy src & "\" & f2, dst & "\" & rf2
    If Err.Number <> 0 Then
        MsgBox "Copy error: " & src & "\" & rfl
    End If
On Error GoTo 0

Dim xL As Excel.Application
Set xL = New Excel.Application
xL.Visible = True
Dim wb As Excel.Workbook
Set wb = xL.Workbooks.Open(F6)

'In case you don't know how here are two ways to reference a sheet:
Dim sh As Excel.Worksheet
Set sh = xL.Sheets(1)

sh.Name = "TestMeOut"

'Saving and closing are important...
wb.Save
Set wb = Nothing
xL.Quit
Set xL = Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

如果它是活动工作表,请使用

ActiveSheet.Name = "New Name"

如果不是活动表,则使用:

Sheets("SheetName").Name = "New Name"

Sheets(2).Name = "New Name"

对于最后一个,索引(示例中为2)是从1开始从左到右计数的工作表编号。

按文件名打开Excel工作簿:

Dim xL As Excel.Application
Set xL = New Excel.Application
xL.Visible = True
Dim wb as Excel.Workbook
Set wb = xl.Workbooks.Open(put your filename here as a literal or variable)

'In case you don't know how here are two ways to reference a sheet:
Dim sh As Excel.Worksheet
Set sh = xL.Sheets("Sheet1")
'    or
Set sh = xL.Sheets(1)

'put your code here

'Saving and closing are important...
wb.Save
Set wb = Nothing
xL.Quit
Set xL = Nothing

注意:要使用Excel参考,请转到Tool =&gt;引用并查找Microsoft Office xx.x对象库(其中xx.x是版本)。