Excel VBA:通过快捷键运行时打开文档后宏挂起,但在 VB 编辑器中完美运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17409524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:59:13  来源:igfitidea点击:

Excel VBA: Macro hangs after opening a document when run via shortcut key, but runs perfectly from VB editor

vbaexcel-vbakeyboard-shortcutsexcel

提问by ForceMagic

I ran into a strange problem, I decided to assign a keyboard shortcut Ctrl + Shift + Pon one of my routine in VBA. This routine is suppose to open an existing excel workbook, copy some informations and .SaveAsanother name.

我遇到了一个奇怪的问题,我决定Ctrl + Shift + P在 VBA 中为我的一个例程分配一个键盘快捷键。此例程假设打开现有的 excel 工作簿,复制一些信息和.SaveAs另一个名称。

This actually runs fine when I hit Play in the Visual Basic Editor. However, when I use the keyboard shortcut inside Excel to run my code, it stop working after opening the document.

当我在 Visual Basic 编辑器中点击播放时,这实际上运行良好。但是,当我使用 Excel 中的键盘快捷键运行我的代码时,它在打开文档后停止工作。

I reproduce the problem in this sample:

我在此示例中重现了该问题:

Public Sub WriteData()
    Dim templatePath As String
    Dim templateWorkbook As Workbook

    'it seems to hang on the following line
    Set templateWorkbook = Application.Workbooks.Open(templatePath)

    With templateWorkbook.Worksheets.Application
        .Range("B3") = "Employee name"
        .Range("B4") = "Employee first name"
        .Range("B5") = "Employee email"
    End With

    templateWorkbook.SaveAs(ThisWorkbook.Path & "Test")
    templateWorkbook.close
End Sub

I am using Excel 2007.

我正在使用 Excel 2007。

回答by ForceMagic

Apparently, after multiples google search about that particular problems, it seems that

显然,在多次谷歌搜索该特定问题之后,似乎

Application.Workbooks.Open(yourPath)

mixed with the Shiftkeyboard key in your shortcut is the problem. More precisely from this guyif you look at the last answer:

与快捷键中的Shift键盘键混合是问题所在。如果你看最后一个答案,更准确地说是这个人

The shift key makes a vb script stop at any Open statement.

shift 键使 vb 脚本在任何 Open 语句处停止。

So you have two solutions

所以你有两个解决方案

  1. Remove the Shiftkey from your shortcut and choose another one

  2. Instead of using .Open, you could use .Addwhich will do the same job, but the code won't hang. So if you do Application.Workbooks.Add(yourPath)it should behave properly.

  1. 从快捷方式中删除Shift键并选择另一个

  2. .Open您可以使用.Addwhich 来完成相同的工作,而不是使用,但代码不会挂起。所以如果你这样做,Application.Workbooks.Add(yourPath)它应该表现得很好。

It is funny though, that both Openand Addhave the exact same behavior when you look at the screen while running the Macro.

很有趣的是,虽然,这两个OpenAdd具有完全相同的行为,当你在看屏幕时运行宏。

Edit:I couldn't find any official link referring to that bug.

编辑:我找不到任何提及该错误的官方链接。