简体   繁体   English

Excel VBA-无法关闭使用Workbook.Add创建的新工作簿

[英]Excel VBA - Cannot Close New Workbook created using Workbook.Add

I have the following code that creates a new workbook and populates it with some data. 我有以下代码创建一个新的工作簿,并用一些数据填充它。

Dim wb as Workbook
Set wb = Workbooks.Add
wb.Range("A1") = "Dummy Text" 'Some code that populates data
wb.Activate 'wb.Activate or ThisWorkbook.Activate has no effect

The new workbook opens fine. 新工作簿可以正常打开。 I am able to minimise it, use the menus, etc. but am unable to click the close button. 我可以将其最小化,使用菜单等,但是无法单击关闭按钮。

If I go back to the original workbook that has the macro and come back to the new workbook, I can close. 如果我回到具有宏的原始工作簿并回到新工作簿,则可以关闭。

How do I overcome this problem? 我该如何克服这个问题? Out of ideas unfortunately. 不幸的是,没有想法。

My desidred use case 我想要的用例

Step 1 : User clicks a button -> A new workbook opens up with data 步骤1:用户单击一个按钮->一个新的工作簿将打开并显示数据

Step 2 : User reads the information in the new workbook and decides to save / close 第2步:用户读取新工作簿中的信息,然后决定保存/关闭

But the close button in the new workbook won't work until the user goes back to the original workbook and comes again to the new workbook. 但是,直到用户返回到原始工作簿并再次进入新工作簿之前,新工作簿中的关闭按钮才起作用。

I think you need to add this line: 我认为您需要添加以下行:

Workbooks("source").Close

if you want to close the current workbook , try this : 如果要关闭当前工作簿,请尝试以下操作:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If ActiveCell.Value = "CLOSE" Then
        ThisWorkbook.Saved = True
        ThisWorkbook.Close
    End If
End Sub
Sub Button1_Click()
Dim wb As Workbook
Set wb = Workbooks.Add
wb.Sheets("Sheet1").Range("A1") = "Dummy Text" 'Some code that populates data
wb.Activate 'wb.Activate or ThisWorkbook.Activate has no effect
End Sub

That worked fine on my excel. 这对我的excel来说效果很好。 I click the close button and it has asked me if i want to save or not. 我单击关闭按钮,它询问我是否要保存。

after your code 在您的代码之后

Dim wb as Workbook
Set wb = Workbooks.Add
wb.Range("A1") = "Dummy Text"

insert 插入

set wb = nothing

this will release your new workbook and you can close using the "X" in the top right. 这将发布您的新工作簿,您可以使用右上角的“ X”关闭。

PS: Sorry my english PS:对不起我的英语

显示用户表单时,请确保使用“ .Show 0”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM