繁体   English   中英

循环文件夹并检查 Excel 文件名是否以工作表名称结尾,然后复制工作表

[英]Loop folder and check if Excel file name ends with worksheet name, then copy worksheet

我需要一些帮助和想法。

我有一个文件夹,比方说这个C:\Users\ Me \Desktop\Test Dir\Files\在这个文件夹中我有几个工作簿和我的主工作簿名为Test.xlsm

在我的主工作簿中,我有几张不同名称的工作表 AB11、AB12、BC13 等

我想构建一个代码,将工作表 AB1 复制并移动到名称以 AB1 结尾(或可能包含该词)的文件夹中的 excel 文件。

然后循环将继续。 如果下一个 Excel 文件以 AB2 结尾,则从我的主工作簿中复制并移动工作表 AB2。

有任何想法吗? 到目前为止我所拥有的是:

但是,找不到我的文件,以名称“AB11”结尾的文件


Dim myPath As String
Dim myFileAB11 As Workbook
Dim wb As Workbook

myPath = "C:\Users\Me\Desktop\Test\Split "

filenamefilters = Array("AB11.xlsx", "AB12.xlsx", "BC13.xlsx", "BC14.xlsx")
myFileAB11 = Dir(myPath & "*AB115*.xls", vbNormal)
myFileAB12 = Dir(myPath & "*AB12*.xls", vbNormal)
myFileBC13 = Dir(myPath & "*BC13*.xls", vbNormal)
myFileBC14 = Dir(myPath & "*BC14*.xls", vbNormal)

Workbooks.Open (Dir(myPath & "*GB55.xlsx", vbNormal))

Workbooks(myFileAB11).Activate
Sheets.Add
ActiveSheet.Name = "AB11"

Workbooks.Open Filename:="C:\Users\Me\Desktop\Test\Test.xlsm"
Sheets(AB11).Copy Before = Workbooks(myFileAB11).Sheets(Sheets.Count)
ActiveSheet.Name = "AB11"



End Sub

我不喜欢人们更有可能用“更加努力”的信息来回应,而不是来自已经解决了这些问题的人的一些实际建议。 下面是一些用于在两个工作簿之间移动工作表的有用代码。 我解释了每一行的作用。

Dim SourceWorkbook As Workbook, CurrentWorkbook As Workbook 'sets up objects references for the workbook files.

Set CurrentWorkbook = ThisWorkbook 'ThisWorkbook is a keyword that references the book this code is running on
Set SourceWorkbook = Workbooks.Open("D:\work files\Warehouse inventory system\Input file.xlsx") 'this will open the file and assign the reference to it to SourceWorkbook

SourceWorkbook.Sheets("Sheet1").Copy After:=CurrentWorkbook.Sheets("Main") 'this code section opens the file, imports the sheet
SourceWorkbook.Close 'Closes the second workbook, recommended to free up resources

Sheets("Sheet1").Activate 'this makes the newly pasted sheet the active sheet
Sheets("Sheet1").Cells.Select 'this will select all cells on that sheet, it is not nessacary to activate the sheet to select the cells
Selection.Copy 'copys the selection to the clipboard
Sheets("Main").Select 'selects the sheet named Main
Cells(1, 1).Select 'selects the first cell in the sheet
ActiveSheet.Paste 'pastes in the data from the other sheet

Application.DisplayAlerts = False 'turns off alert messages before deleting to remove the "are you sure" message
Sheets("Sheet1").Delete 'deletes the sheet named "Sheet1"
Application.DisplayAlerts = True 'turns on the alert messages after the delete
Sheets.Add(After:=Sheets("Main")).name = "Barcode" 'adds a new sheet and names it Barcode
Sheets("Main").Select 'selects the Main sheet

您当然必须弄清楚如何修改此代码以使其适合您的情况。 但它应该足以让你开始。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM