我正在尝试学习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,如果那有关系的话。