使用GetObject编辑其他工作簿可以工作1次

首先,我是一个begginer。 任何build议,欢迎! 只是试图在工作中的代码,以节省时间后pipe理100多个文件。

我正在构build一个Excelmacros,和其他许多用户一样,我正在尝试执行以下操作:

  • 让macros“驻留”在工作簿“A”中。
  • 使用工作簿“B”中的键盘快捷键触发macros
  • 让macros在工作簿“B”(其中包括从工作簿“C”复制工作表)中发挥其魔力

这涉及到,在某些时候,提示用户input工作簿“C”,定义一个variables并将工作簿C放入其中。

下面的代码是macros的一部分,只用了一次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" 

任何人都已经遇到这样的麻烦? 非常感谢你!

使用GetObject将引用设置为已经打开的外部应用程序。 以同样的方式使用CreateObject设置创build一个新的外部应用程序。

  • 添加了一个检查,看看是否打开了一个同名的工作簿。
  • 删除设置DestWkb = ActiveWorkbook
  • 改用ThisWorkBook
  • 添加有趣的消息,所以你知道它的工作。
  Dim fd As FileDialog Dim ffs As FileDialogFilters Dim SourceWkb As Workbook Dim SourceWkbPath As String Dim SourceWkbShortName As String '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 .Show SourceWkbPath = fd.SelectedItems(1) SourceWkbShortName = Mid(SourceWkbPath, InStrRev(SourceWkbPath, "\") + 1) End With On Error Resume Next Set SourceWkb = Workbooks(SourceWkbShortName) If Err.Number <> 0 Then Set SourceWkb = Workbooks.Open(SourceWkbPath) End If On Error GoTo 0 MsgBox """Hello World!""", vbInformation, SourceWkb.Name & " Says:"