这是我尝试过的代码。但它卡在查找单元格(Set RangeObj = Cells.find
)。
请检查以下代码:
Sub CopyFromFile()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:UsersNazmul Hossain AkashDesktopPlay ExcelFinal"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "zmaster.xlsm" Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
Range("B2:D18").Copy
Set RangeObj = Cells(1, "A")
ActiveWorkbook.Close
Set RangeObj = Cells.Find(What:=RangeObj, After:=ActiveCell, _
LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False)
If RangeObj Is Nothing Then MsgBox "Not Found" Else RangeObj.Select
ActiveCell.Offset(rowOffset:=2, columnOffset:=0).Activate
ActiveSheet.PasteSpecial
MyFile = Dir
Loop
End Sub
我想我看到了问题。你仍然没有Dim
你的RangeObj
(我在顶部没有看到Option Explicit
!- 请添加它)。这将使您Dim
每个变量,因此您必须决定变量的数据类型,包括RangeObj
。RangeObj
这里有一个问题。由于您确实Set RangeObj = Cells.Find()
,因此可以将其作为范围对象。但是,在此之前,您Set RangeObj = ActiveWorkbook.Cells(1, "A")
- 您Set
它。这是一个错误,因为这样你得到一个对象,然后你想在.Find()
中使用它。你应该传递给.Find()
任何东西,但不能传递给对象。让我们尝试解决问题:
-
在最顶部插入此行:
选项显式
-
调暗您的范围:
调暗范围作为范围
-
引入另一个用于存储文本的变量
.find()
:将范围字符串调暗
-
将
Set RangeObj = ActiveWorkbook.Cells(1, "A")
替换为RangeStr = ActiveWorkbook.Cells(1, "A").Value
-
将
Cells.Find(What:=RangeObj,
替换为Cells.Find(What:=RangeStr,
让我们看看它带来了什么。