VBA导入数据:如果不存在则排除工作表

时间:2018-05-27 15:35:42

标签: vba loops import

我构建了这段代码,用于从工作簿导入数据并将其粘贴到另一个工作簿。原始工作簿由数百张纸组成(每个国家/地区一张,由ISO 2数字代码标识:AE,AL,AM,AR等......)。宏打开这些工作表中的每一个,复制相同的单元格,并在新工作簿中打印所有这些单元格。 问题是,例如,如果纸张F(AM)不存在,则宏停止。我想确保如果纸张不存在,宏将继续所有其他纸张(即F(AR),F(AT),F(AU))直到结束。 有人有什么建议吗? 非常感谢提前!

    Sub ImportData()
    Dim Wb1 As Workbook
    Dim MainBook As Workbook
    Dim Path As String
    Dim SheetName As String

    'Specify input data
    Path = Worksheets("Input").Range("C6").Value
    'Decide in which target sheet print the results
    SheetName = "Data"
    'From which sheets you need to take the data?
    OriginSheet145 = "F(AE)"
    OriginSheet146 = "F(AL)"
    OriginSheet147 = "F(AM)"
    OriginSheet148 = "F(AR)"
    OriginSheet149 = "F(AT)"
    OriginSheet150 = "F(AU)"
    'Set the origin workbook
    Set Wb1 = Workbooks.Open(Path & "_20171231.xlsx")
    'Set the target workbook
    Set MainBook = ThisWorkbook

    'Vlookup to identify the correct data point
    Wb1.Sheets(OriginSheet145).Range("N25").FormulaR1C1 = "=VLOOKUP(""010"",C[-10]:C[-7],2,FALSE)"
    Wb1.Sheets(OriginSheet146).Range("N26").FormulaR1C1 = "=VLOOKUP(""010"",C[-10]:C[-7],2,FALSE)"
    Wb1.Sheets(OriginSheet147).Range("N27").FormulaR1C1 = "=VLOOKUP(""010"",C[-10]:C[-7],2,FALSE)"
    Wb1.Sheets(OriginSheet148).Range("N28").FormulaR1C1 = "=VLOOKUP(""010"",C[-10]:C[-7],2,FALSE)"
    Wb1.Sheets(OriginSheet149).Range("N29").FormulaR1C1 = "=VLOOKUP(""010"",C[-10]:C[-7],2,FALSE)"
    Wb1.Sheets(OriginSheet150).Range("N30").FormulaR1C1 = "=VLOOKUP(""010"",C[-10]:C[-7],2,FALSE)"
    'Copy the data point and paste in the target sheet
    Wb1.Sheets(OriginSheet145).Range("N25").Copy
    MainBook.Sheets(SheetName).Range("AW5").PasteSpecial xlPasteValues
    Wb1.Sheets(OriginSheet146).Range("N26").Copy
    MainBook.Sheets(SheetName).Range("AW6").PasteSpecial xlPasteValues
    Wb1.Sheets(OriginSheet147).Range("N27").Copy
    MainBook.Sheets(SheetName).Range("AW7").PasteSpecial xlPasteValues
    Wb1.Sheets(OriginSheet148).Range("N28").Copy
    MainBook.Sheets(SheetName).Range("AW8").PasteSpecial xlPasteValues
    Wb1.Sheets(OriginSheet149).Range("N29").Copy
    MainBook.Sheets(SheetName).Range("AW9").PasteSpecial xlPasteValues
    Wb1.Sheets(OriginSheet150).Range("N30").Copy

    MainBook.Save
    Wb1.Close savechanges:=False

    MsgBox "Data: imported!"

    End Sub

1 个答案:

答案 0 :(得分:0)

此函数返回TRUEFALSE,指示工作簿对象中是否存在 string wsName中命名的工作表

Function wsExists(wb As Workbook, wsName As String) As Boolean
    Dim ws: For Each ws In wb.Sheets
    wsExists = (wsName = ws.Name): If wsExists Then Exit For
    Next ws
End Function

如果工作表不存在,请使用IF语句跳过适用的代码。

编辑:

我可以说你在你的代码中投入了大量的工作,这很棒,所以当我说它让我焦虑时不要采取错误的方式,所以我必须简化它。 ......有很多不必要的步骤。

我确实认为“正确的方式”是“无论什么方式都有效”,所以kudo就是这么做的。编程中有一个陡峭的学习曲线,所以我想我会提供一个替代代码块来替换你的。 (Option Explicit位于模块的最顶层,将“强制”您正确声明/处理变量,对象等。)

如果没有看到您的数据,我无法保证这会有效 - 事实上,如果您选择使用此功能,很可能会在某个地方出现错误的单元格引用 - 如果您选择使用此功能。

Option Explicit

Sub ImportData()

    Const SheetName = "Data" 'destination sheet name
    Const sourceFile = "_20171231.xlsx" 'source filename for some reason
    Dim wbSrc As Workbook, wbDest As Workbook, sht As Variant
    Dim stPath As String, arrSourceSht() As Variant, inRow As Long

    Set wbDest = ThisWorkbook 'dest wb object
    stPath = Worksheets("Input").Range("C6").Value 'source wb stPath
    'create array of source sheet names "146-150":
    arrSourceSht = Array("F(AE)", "F(AL)", "F(AM)", "F(AR)", "F(AT)", "F(AU)")
    Set wbSrc = Workbooks.Open(stPath & sourceFile) 'open source wb

    With wbSrc
        'VLookup to identify the correct data point
        inRow = 5 'current input row
        For Each sht In arrSourceSht
            If wsExists(wbSrc, CStr(sht)) Then
                wbDest.Sheets(sht).Range("AW" & inRow) = Application._
                  WorksheetFunction.VLookup("010", Range(.Sheets(sht).Range("N" & _
                  20 + inRow).Offset(-10), .Sheets(sht).Range("N" & 20 + inRow).Offset(-7)), 2, False)
            End If
            inRow = inRow + 1 'new input row
        Next sht

        wbDest.Save 'save dest
        .Close savechanges:=False 'don't save source

    End With
    MsgBox "Data: imported!"

End Sub

Function wsExists(wb As Workbook, wsName As String) As Boolean
    Dim ws: For Each ws In wb.Sheets
    wsExists = (wsName = ws.Name): If wsExists Then Exit For
    Next ws
End Function

如果您有任何问题,请告诉我,如果您愿意,我可以向您介绍它的工作原理。 (我每天至少在这里一次。)