VBA循环浏览文件夹找到工作表打开它并将所有选项卡移动到另一个工作簿

时间:2015-12-17 02:02:03

标签: excel vba excel-vba

我正在开展一个需要以下项目的项目:

我想要一个宏来遍历文件夹并搜索某个工作表,然后从该工作表中获取所有选项卡并将它们移动到合并的工作簿

是否可以根据工作表名称中的某个字符串查找工作表?例如:Financial_data_401kk.xls

你能用这个字符串搜索" 401kk"?

我是VBA的新手,这是我到目前为止所做的

Sub ConsolidateSheets()

Dim Path as String
Dim File As String

Dim wb1 as Workbook, wb2 as Workbook    

Path = "G:\Operations\test\"    
File = Dir(Path & "*401kk*")

Set wb1 = Wworkbooks("book1.xlsm")
Set wb2 = Workbooks(File)

For Each sh in wb2
    sh.copy After:=wb1.sheets(wb1.sheets.count)
Next

End Sub

2 个答案:

答案 0 :(得分:2)

在此EE article的基础上,你可以做到这一点。

密钥更新是这两行

each_with_index

第一个点根据Loop through files in a folder using VBA?使用strFileName = Dir(strFolderName & "\*401kk*.xls*") strDefaultFolder = "G:\Operations\test\" 搜索您的特定字符串,因此只会处理所需的工作簿。

Dir

答案 1 :(得分:0)

您可以操纵以下内容以满足您的需求。在if语句中添加多个OR子句,并适当调整文件夹路径!它会将工作表转移到持有代码的工作簿中!

Sub main()

Dim fso As New Scripting.FileSystemObject
Dim file As Scripting.file
Dim fldr As Scripting.Folder
Dim wb As Excel.Workbook
Set fldr = fso.GetFolder("c:\excelfiles\")
Dim target As String

Dim cwb As Workbook
Set cwb = ActiveWorkbook

For Each file In fldr.Files()
target = file.Name

If file.Name = "tasks.xlsx" Then
i = 1
Application.Workbooks.Open (fldr.Path & "\" & file.Name)
Set wb = Application.Workbooks(target)
    For Each sht In wb.Sheets
         If wb.Sheets(i).Name = "home" Then
            wb.Sheets(i).Copy after:=cwb.Sheets(1)
            i = i + 1
        End If
    Next
End If
Next

Set wb = Nothing
Set file = Nothing
Set fldr = Nothing
Set xls = Nothing
Set fso = Nothing

End Sub