解决Excel VBA中的运行时错误

3

我正在尝试学习Excel VBA,并有很多需要学习的内容。

通过这个宏,我正在设置一个文件,使我能够根据个人姓名从每周报告中复制/粘贴特定范围的数据。本质上,我希望能够让个人点击一个按钮,自动获取数据。以下是我迄今为止编写的代码:

子程序1(个人定义他们的姓名):

Sub Button1_Click()
Dim Name As Variant
Name = InputBox("Enter your name as it appears on the report", "Enter Name")
Worksheets("Summary").Range("A1").Value = Name
Application.ScreenUpdating = True
ActiveWorkbook.Save
End Sub

子程序2(基于在子程序1中输入的名称从报告中提取数据的宏):

Sub Report1_Click()
Dim Name As Variant
Set Name = Worksheets("Summary").Range("A1").Value
'check if Name is entered
If Name = "" Then
MsgBox ("Your name is not visible, please start from the Reference tab.")
Exit Sub
End If
Dim SourceFile As Workbook
Set SourceFile = Workbooks("filename.xlsm")
'check if source file is open
If SourceFile Is Nothing Then
'open source file
Set SourceFile = Workbooks.Open("C:\filename.xlsm")
SourceFile.Activate
Else
'make source file active
SourceFile.Activate
End If

Dim DestFile As Variant

Set DestFile = ActiveWorkbook.Worksheets("Input").Range("B2")

Dim ActiveCell As Variant

Set ActiveCell = Workbooks("filename.xlsm").Worksheets("Group").Range("A1")

Cells.Find(What:=Name, After:=ActiveCell, LookIn:=xlFormulas _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False).Activate

ActiveSheet.Range("$A$2:$DQ$11").AutoFilter Field:=1, Criteria1:=Name
Range("A7:CD7").Select
Selection.Copy
DestFile.Activate
ActiveSheet.Paste

Application.ScreenUpdating = True

ActiveWorkbook.Save

End Sub

在Sub 2中,我在这行上得到了一个运行时错误13(“类型不匹配”),但我不知道为什么:
```Set Name = Worksheets("Summary").Range("A1").Value```
在不同的时间点,我也会得到不同的错误(包括91、1004和9),如果这个问题得到解决,这些错误可能会再次出现,也可能不会。
更新:通过删除Set(至少我认为是这样),我解决了前一行的错误13,但现在我在这里得到了一个错误91: ```Cells.Find(What:=Name, After:=ActiveCell, LookIn:=xlFormulas _ , LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False).Activate``` 同样,我是新手,非常感谢任何帮助。
编辑:我使用的是Excel 2011 for Mac,如果那有关系的话。

不需要将名称放到工作表上,变量可以很好地保存它。 - findwindow
我难道不需要设定变量以确保它从第一个子程序中提取值吗?我可能误读了你的评论(归因于经验不足)。 - WhalesLarry
两个不同的变量可以引用相同的值吗?比如,如果我有子程序1的变量标记为X和子程序2的变量标记为Y,但它们都从同一个位置获取,这样行得通吗? - WhalesLarry
另外,我按照你建议的更改了关于“设置”变量的部分,但现在在Sub 2中的Cells.Find字符串上出现了运行时错误91。 - WhalesLarry
你是删除了单词“Set”还是整行代码? - Davesexcel
显示剩余4条评论
1个回答

4

因为你正在激活一个不存在的对象。

最好在尝试激活之前,先检查Cells.Find()是否返回了Range(或者返回了Nothing)。

'Create a temporary Range
Dim temp_range As Range

'Notice that i removed the activation of the range at the end
Set temp_range = Cells.Find(What:=Name, After:=activecell, LookIn:=xlFormulas _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False)

'before anything, test if it's nothing...
If Not temp_range Is Nothing Then
    ' if not the you can activate..
     temp_range.Activate
    ' and work on the result...
    Debug.Print temp_range.Value , temp_range.Address
End If

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接