.Find()在通过另一个excel文件打开的excel文件中不起作用

我正在一个Excel文件,我需要从另一个Excel文件,我正在使用VBAmacrosinput采取数据。 现在,如果我从input文件复制整个数据,并将其粘贴在主文件,然后工作。 但我只想从input文件中select数据,所以我使用.Find()来获取所需的数据,但.Find()不在这个input文件中工作,虽然同样的事情在任何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 

—————–此代码不起作用——————–在上面的代码中,如果我replace

  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是一个Rangevariables,它不工作,因为rng是没有任何东西的。

你可以请检查我做错了,因为如果我使用相同的代码行来find它的工作原理。

非常感谢

最好你应该创build一个你想要search的工作簿的引用,然后创build你想要search的工作表。 这是一个最小的例子:

 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