簡體   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