【发布时间】:2016-10-17 06:42:21
【问题描述】:
首先,我是一个初学者。欢迎任何建议!只是尝试在工作中编写代码以节省以后管理 100 多个文件的时间。
我正在构建一个 Excel 宏,并且与许多其他用户一样,我正在尝试执行以下操作:
- 让宏“驻留在”工作簿“A”中。
- 使用工作簿“B”中的键盘快捷键触发宏
- 让宏在工作簿“B”中发挥作用(包括从工作簿“C”复制工作表)
这包括在某些时候提示用户输入工作簿“C”,定义一个变量并将工作簿 C 放入其中。
以下代码是宏的一部分,仅在 x 中运行一次,并且显然“崩溃”而没有警告或错误代码,甚至让我知道它已经崩溃。
'All the following code is in workbook "A"
Dim fd As FileDialog
Dim ffs As FileDialogFilters
Dim DestWkb As Workbook
Dim SourceWkb As Workbook
Dim SourceWkbPath As String
'Set active workbook as destination workbook (this is workbook "B")
Set DestWkb = ActiveWorkbook
'Prompt user for source workbook (this will be workbook "C")
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
Set ffs = .Filters
With ffs
.Clear
.Add "Excel", "*.xlsx"
End With
.AllowMultiSelect = False
If .Show = False Then Exit Sub
SourceWkbPath = fd.SelectedItems(1)
End With
'Here is where it starts to go wrong..
'This message box will show up with correct data in it :
MsgBox SourceWkbPath
'This line seems to work, as I can see in VB the workbook specified by the user
Set SourceWkb = GetObject(SourceWkbPath)
'From here... it's like there was an Exit Sub. I will rarely see the following msgbox :
MsgBox "Success"
有人遇到过这样的麻烦吗?非常感谢!
【问题讨论】:
-
代码对我来说很好用。您可以在单步执行代码时使其崩溃吗?或仅在直接通过时。有错误处理吗?
-
我会改用
Workbooks.Open(SourceWkbPath)。 -
道格的好建议。直接使用图书
-
确实,代码在其驻留的工作簿中直接执行时可以正常工作。但是,当从另一个工作簿(通过键盘快捷键触发)执行时,它几乎不会在 20 次中工作 1 次......无论是通过步进还是直接运行。我已经尝试过 Workbooks.Open,但似乎并没有好转。会再试一次。谢谢!