.Find()在通过另一个excel文件

时间:2016-07-04 04:05:37

标签: excel vba excel-vba

我正在处理一个excel文件,我需要从另一个excel文件中获取数据,我使用VBA宏作为输入。现在,如果我从输入文件中复制整个数据并将其粘贴到主文件中,那么这是有效的。但我只想从输入文件中选择数据,所以我使用.Find()来获取所需的数据,但.Find()在这个输入文件中不起作用,尽管在任何excel文件中都可以使用相同的东西。

以下是我正在使用的示例代码:

-----这段代码有效------

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

    Dim responseworkbook As Workbook
    Dim macroworkbook As Workbook

    Set macroworkbook = ActiveWorkbook

    strFileToOpen = Application.GetOpenFilename _
    (Title:="Please choose a file to capture input data")

    If strFileToOpen = "" Then
        MsgBox "Please select a valid input file!"
        Exit Sub
    Else
        Workbooks.Open Filename:=strFileToOpen
        Set responseworkbook = ActiveWorkbook
        strOpenFile = ActiveWorkbook.Name
    With ActiveSheet
                lastColumn_res = .Cells(1,         Columns.Count).End(xlToLeft).Column
                lastrow_res = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With
        For j = 1 To 1
            responseworkbook.Activate
            If Cells(1, j).Value = "ABC" Then 'ABC is column name
                Range(Cells(2, j), Cells(lastrow_res, j + 1)).Copy
                macroworkbook.Activate
                Sheets("selected data").Select
                With ActiveSheet
                    firstrow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
                End With
                Range("D" & firstrow).Select
                Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
       End If
    End If

-----------------此代码不起作用-------------------- 在上面的代码中如果我替换

    Range(Cells(2, j), Cells(lastrow_res, j + 1)).Copy

    rng = responseworkbook.Worksheets(1).Range("A:C").Find("12/31/2001")
    or
    rng = Sheets(1).Range("A:C").Find("12/31/2001", , xlValues, xlWhole)
    or
    rng = .Find("12/31/2001", , xlValues, xlWhole)

这里rng是一个Range变量,它不起作用,因为rng没有任何结果。

请问我在哪里做错了,因为如果我使用相同的代码行来查找它的数据。

非常感谢

1 个答案:

答案 0 :(得分:1)

最好是创建对要搜索的工作簿的引用,然后创建要搜索的工作表。这是一个最小的例子:

Option Explicit

Sub FindInOtherWorkbook()

    Dim wbTarget As Workbook
    Dim wsTarget As Worksheet
    Dim rngTarget As Range

    Set wbTarget = Workbooks.Open("C:\Users\Robin\Desktop\foo.xlsx")
    Set wsTarget = wbTarget.Worksheets("Sheet1")
    'you can change Range("A1:F20") to whatever area you need to search in
    Set rngTarget = wsTarget.Range("A1:F20").Find(What:="foo")
    'use line below to search all cells of wsTarget worksheet
    'Set rngTarget = wsTarget.Cells.Find(What:="foo")

    If rngTarget Is Nothing Then
        Debug.Print "Cannot find foo"
    Else
        Debug.Print "Found cell at: " & rngTarget.Address
        Debug.Print "Found cell in sheet: " & rngTarget.Worksheet.Name
        Debug.Print "Found cell in book: " & rngTarget.Parent.Parent.Name
    End If

    wbTarget.Close SaveChanges:=False

End Sub