簡體   English   中英

復制工作表並創建主工作簿后重命名工作表

[英]Rename Sheet after it is copied and Create Master Workbook

以下是用於從源中復制工作表,然后重命名並放置到目標中的代碼。

我想擴展功能以使用另一個單元格引用在新創建的文件中重命名工作表名稱。 (請注意,每個復制的工作簿只有一個工作表。)然后,在所有工作簿被復制,重命名和工作表重命名之后,將目標路徑中的所有工作簿合並為一個。

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

如果是活動表,請使用

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引用,請轉到“工具=>引用”,然后查找Microsoft Office xx.x對象庫(其中xx.x是版本)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM