[英]Specify name of sheet in VBA
I have this vba code that puts sheet1 of all workbooks in a folder in as sheets in one workbook.我有这个 vba 代码,它将所有工作簿的 sheet1 放在一个文件夹中,作为一个工作簿中的工作表。 This works all fine.这一切正常。
What I want to do is change the name of each sheet that is copied in to my workbook.我想要做的是更改复制到我的工作簿中的每张工作表的名称。 Then I want to overwrite the files that already exists in the workbook.然后我想覆盖工作簿中已经存在的文件。
Hope someone can help me with a solution.希望有人可以帮助我解决问题。
Sub CombineFilesInSheets()
Dim Path As String
Dim FileName As String
Dim Wkb As Workbook
Dim WS As Worksheet
Application.EnableEvents = False
Application.ScreenUpdating = False
Path = "*The path*" 'Change as needed
FileName = Dir(Path & "\*.xls", vbNormal)
Do Until FileName = ""
Set Wkb = Workbooks.Open(FileName:=Path & "\" & FileName)
Worksheets("Sheet1").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Wkb.Close False
FileName = Dir()
Loop
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
There are a couple ways to go about your request, and not to steal from /u/VBasic2008, but he's on a similar line of thinking to me.有几种方法可以满足您的要求,而不是从 /u/VBasic2008 窃取,但他的想法与我相似。
'open workbook like you do
Set Wkb = Workbooks.Open(FileName:=Path & "\" & FileName)
'perform your regular copy
Worksheets("Sheet1").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
'define a name
dim desiredSheetName as string
desiredSheetName = Wkb.Name 'takes the workbook name
'check if the desired name exists, and if so, delete the old sheet
If Not IsError(Evaluate(desiredSheetName & "!A1")) Then ThisWorkbook.Sheets(desiredSheetName).Delete
'name the last added sheet in ThisWorkbook the desired name
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = desiredSheetName
You could similarly use the check to do nothing if the desiredSheetName
already exists, though I believe the above fits your post.如果所需的desiredSheetName
已经存在,您可以类似地使用检查不执行任何操作,但我相信以上内容适合您的帖子。
我通过之后运行一个宏来删除和编辑工作表的名称来解决这个问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.