搜索工作表并将工作表从一个工作簿复制到另一个工作簿

时间:2016-11-19 15:00:14

标签: excel vba

我有一个包含宏的工作簿(wb1)。我通过在msgbox中选择它来打开文件(wb)。

我想循环浏览所有wb表格,如果像“ xxx ”这样的sheet.name在第一张表格之前保存wb1中的表格副本。

Sub GetFile()

    Dim fNameAndPath As Variant, wb As Workbook
    Dim wb1 As ThisWorkbook

    fNameAndPath = Application.GetOpenFilename(FileFilter:="All Files (*.*),*.*", _
      Title:="Sélectionner le fichier des extractions Magnitude sur la Phase IAS CONSO")

    If fNameAndPath = False Then Exit Sub

    Set wb = Workbooks.Open(fNameAndPath)

    For Each Sheet In wb.Sheets

        If LCase(Sheet.Name) Like "*Sheet1*" Then
            Range("A2").Select
            'ActiveSheet.Delete
        End If

    Next Sheet

1 个答案:

答案 0 :(得分:0)

试试这个:

Option Explicit

Sub GetFile()
    Dim fNameAndPath As Variant
    Dim sht As Worksheet

    fNameAndPath = Application.GetOpenFilename(FileFilter:="All Files (.),.", Title:="Sélectionner le fichier des extractions Magnitude sur la Phase IAS CONSO")
    If fNameAndPath = False Then Exit Sub

    Set wb = Workbooks.Open(fNameAndPath)
    For Each sht In wb.Sheets
        If LCase(sht.Name) Like "*sheet1*" Then sht.Copy Before:=ThisWorkbook.Sheets(1)
    Next sht
    wb.Close False '<--| close the newly opened workbook without saving it
End Sub

还注意我改变了:

If LCase(sht.Name) Like "*Sheet1*"

为:

If LCase(sht.Name) Like "*sheet1*"

否则检查永远不会返回True,因为它将全部小写字符串(LCase(sht.Name))与一个大写字符(“S”)的字符串进行比较