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

时间:2016-06-15 23:30:20

标签: excel vba excel-vba macros

首先,我是一个乞丐。欢迎任何建议!只是尝试在工作中编码以节省管理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"

有人已经遇到过这样的麻烦吗?非常感谢你!

1 个答案:

答案 0 :(得分:0)

使用GetObject设置对已打开的外部应用程序的引用。以相同的方式使用CreateObject设置创建新的外部应用程序。

  • 添加了一项检查,以确定是否打开了同名的工作簿。
  • 删除Set 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:"
&#13;
&#13;
&#13;

MSDN说:ThisWorkbook总是返回运行代码的工作簿。

问题是:&#34;如果WorkBook A在工作簿B中运行宏,那么ThisWorkBook会引用什么?

WorkBook A

Sub RunExternalCode()
   WorkBookAName= ThisWorkBook.Name

   WorkBookBName = Application.Run ""

End Sub
  

WorkBook B

Function GetThisWorkBooksName()
    GetThisWorkBooksName = ThisworkBook.Name
End Function

结果:

  

WorkBookAName =&#34; WorkBookA&#34;

     

WorkBookBName =&#34; WorkBookB&#34;