Excel VBA - Cannot Close New Workbook created using Workbook.Add - vba

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
Step 2 : User reads the information in the new workbook and decides to save / close
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.

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.
P.S.: Sorry my english

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. I click the close button and it has asked me if i want to save or not.

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

When displaying your userform, make sure you use ".Show 0".

Related

Opening workbook from file and updating link in original workbook

I'm trying to write a macro in VBA, that will open another Workbook using a PathFile specified in a cell (this works), updates link in workbook in which macro is used (doesn't work) and closes the PathFile workbook (works)
This is a code:
Sub UpdateRaw()
Dim CurrWb As Workbook
Dim FilePath As String
Dim book As Excel.Workbook
Set CurrWb = ActiveWorkbook
FilePath = Range("I1").Value
Dim app As New Excel.Application
app.Visible = True 'so we can see whether correct file is being opened
Set book = app.Workbooks.Open(FilePath)
CurrWb.Activate
Worksheets("Raw_vs_Actual").EnableCalculation = False
Worksheets("Raw_vs_Actual").EnableCalculation = True
book.Close SaveChanges:=False
app.Quit
Set app = Nothing
End Sub
Going step by step I found that command CurrWb.Activate doesn't take me back to my original Workfile. My suspicion is that by opening new Excel Application I can't get back to the CurrWb (ActiveWorkbook). Is there a workaround? I need this so my INDIRECT function doesn't return #REF.
I'm using Excel 2010 in case it's important.
I think Set book = app.Workbooks.Open(FilePath) shall be enough, but if not refresh the workbook:
book.RefreshAll
for opened workbook. For the workbook that contains the macro, use
ThisWorkbook.RefreshAll

Excel VBA - Copy Workbook into a new Workbook with the macros

So I have a worksheet that generates a chart type of thing using information on 2 other worksheets. On It I have an extract button which should copy the entire workbook into a new workbook whilst making the sheets where the data is pulled from invisible to the user. My issue is, the chart worksheet has other features which require macros to be run, for example buttons that hide some of it etc. The issue is I cannot find whether its actually possible to copy through macros from a workbook into the new copied workbook? Anyone have an answer to this and if so, how would you do this? Here is the code I currently have which copies the workbook into a new workbook:
Sub EWbtn()
Dim OriginalWB As Workbook, NewCRCWB As Workbook
Set OriginalWB = ThisWorkbook
Set NewCRCWB = Workbooks.Add
OriginalWB.Sheets("Generator").Copy Before:=NewCRCWB.Sheets("Sheet1")
OriginalWB.Sheets("Module Part Number Tracker").Copy Before:=NewCRCWB.Sheets("Generator")
OriginalWB.Sheets("CRC").Copy Before:=NewCRCWB.Sheets("Module Part Number Tracker")
Application.DisplayAlerts = False
NewCRCWB.Worksheets("Generator").Visible = False
NewCRCWB.Worksheets("Module Part Number Tracker").Visible = False
NewCRCWB.Worksheets("Sheet1").Delete
Application.DisplayAlerts = True
End Sub
I'd take a copy of the original file and delete/hide sheets from that.
All code is copied over as part of the save.
Sub Test()
Dim wrkBk As Workbook
Dim sCopyFileName As String
Dim wrkSht As Worksheet
sCopyFileName = "C:\MyFolderPaths\Book2.xlsm"
'Create copy of original file and open it.
ThisWorkbook.SaveCopyAs (sCopyFileName)
Set wrkBk = Workbooks.Open(sCopyFileName)
'wrkbk.Worksheets does not include Chart sheets.
'wrkbk.Sheets would take into account all the types of sheet available.
For Each wrkSht In wrkBk.Worksheets
Select Case wrkSht.Name
Case "Generator", "Module Part Number Tracker"
wrkSht.Visible = xlSheetVeryHidden
Case "CRC"
'Do nothing, this sheet is left visible.
Case Else
Application.DisplayAlerts = False
wrkSht.Delete
Application.DisplayAlerts = True
End Select
Next wrkSht
wrkBk.Close SaveChanges:=True
End Sub
I managed to find an answer to my question.. This code works fine however you need to add "Microsoft Visual Basic for Applications Extensibility 5.x" as a reference via Tools -> References. Here is the code:
Dim src As CodeModule, dest As CodeModule
Set src = ThisWorkbook.VBProject.VBComponents("Sheet1").CodeModule
Set dest = Workbooks("Book3").VBProject.VBComponents("ThisWorkbook") _
.CodeModule
dest.DeleteLines 1, dest.CountOfLines
dest.AddFromString src.Lines(1, src.CountOfLines)
Credit: Copy VBA code from a Sheet in one workbook to another?

Using VBA to copy a spreadsheet from a secondary workbook into the primary one

I need to take a spreadsheet and compare it with a spreadsheet from another workbook. I know that I can do this using VBA, but I will need to copy a spreadsheet from another workbook so that both spreadsheets will reside within the same workbook and be accessible for comparison. How do I copy a spreadsheet from one workbook into another using VBA?
You don't need to copy the worksheets over to compare them. Simply open both WorkBooks and and set reference to there WorkSheets.
Sub CompareWorkBooks()
Dim wbPending As Workbook
Dim wsPending As Worksheet
Set wbPending = Workbooks("Items Pending")
Set wsPending = wsPending.Worksheet("Items")
Dim wbRecieved As Workbook
Dim wsRecieved As Worksheet
Set wbRecieved = Workbooks("Items Recieved")
Set wsRecieved = Worksheet("Items")
End Sub
If you provide names for Workbooks & WorkSheets and provide column information, we can give you better answers in a shorter period of time. Don't be afraid to post your code either.
If you want a user to select the target workbook and worksheet:
Create a userform
Declare targetWorkbook and tartgetWorksheet at the top of the code module
Add a command button and a combo box
When the button is clicked a file dialog is opened
A reference is now set to the open file
The names of all the worksheets are added to the combo
Changing the combo box value will set the refernce to tartgetWorksheet
Option Explicit
Public targetWorkbook As Workbook
Public tartgetWorksheet As Worksheet
Private Sub CommandButton1_Click()
Dim targetWorkbook As Workbook
Dim ws As Worksheet
Set targetWorkbook = getTargetWorkbook
If targetWorkbook = Nothing Then
MsgBox "Sowmthing went wrong", vbCritical, "Try Again"
Else
For Each ws In targetWorkbook.Worksheets
ComboBox1.AddItem ws.Name
Next
End If
End Function
Function getTargetWorkbook() As Workbook
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
On Error Resume Next
Set getTargetWorkbook = Application.Workbooks.Open(.SelectedItems(1))
On Error GoTo 0
End With
End Function
Private Sub ComboBox1_Change()
Set tartgetWorksheet = targetWorkbook.Worksheets(ComboBox1.Value)
End Sub

Using Excel VBA, how do I keep my original code executing after a 'thisworkbook.close' event in a 2nd workbook?

In Excel 2007, I have a sheet with a list of other Excel documents, all of which have their own VBA. My code opens the first workbook on the list, lets its vba run, then when it has completed, marks it as complete, and opens the next workbook in the list.
All this works fine unless I let one of the other workboks close itself with 'thisworkbook.close'. This stops the VBA running in the original workbook, as well as itself. If I comment this line out, it all works, but I would rather keep just the master workbook and one sub workbook open at one time.
Also, it is unpractical in this case to move all the VBA to the master workbook.
The code before is a highly simplified version to show the issue:
Workbook1's code:
Sub RunReports()
Dim wkb1 As Workbook
Dim wks1 As Worksheet
Dim lngR As Long
Dim strReport As String
Set wkb1 = ThisWorkbook
Set wks1 = wkb1.Sheets(strDay)
For lngR = 4 To 1048576
strReport = wks1.Cells(lngR, 1).Value
'open the report. Its own VBA will take care of everything else
Workbooks.Open strReport
'mark the report as complete
wks1.Cells(lngR, 2).Value = "done"
Next lngR
End Sub
the code in the worksheets that are opened:
Private Sub Workbook_Open()
ThisWorkbook.Sheets("Sheet1").Cells(1, 1).Value = Now()
ThisWorkbook.Save
Application.Wait (Now() + TimeValue("00:00:05"))
ThisWorkbook.Close
End Sub
If I comment out 'thisworkbook.close', it will open them all, update the time they were opened, and save them. If not, it does everything up to the first 'thisworkbook.close', closes the first sub workbook, and stops all VBA execution.
Does anyone have any ideas how to keep the "master" workbook's vba code running after the "sub" workbook's code has finished, when the 'sub' workbook's code contains a 'thisworkbook.close' (edited to make the question clear)
Use standard COM ways of doing things. Take a reference to each workbook (not excel.application) using GetObject(filename). Do what you want then don't close it in sub book, but set the reference to nothing in your master (which happens when you do set exceldoc = nothing or reach an End Function/Sub). Don't do both as that's voodoo programming.

Open excel sheet from form

I have made a form with several command buttons which open specifics worksheets. The problem is when I open an excel file from the command button, if the form is not hidden then I'm not able to click on the opened file(Its not activated)
Even if I hide the form, I need to manually goto that file from taskbar it doesn't get activated.
The problem is:
I don't want my form to be hidden because I want the user to be able to open multiple sheets
The opened sheet doesn't get activated.
Here's my code:
Private Sub CommandButton1_Click()
Dim Wb As Excel.Workbook
Set Wb = Workbooks.Open(Filename:="D:/power system design/foo.xlsx", ReadOnly:=False)
UserForm1.Hide
Wb.Activate
Wb.Sheets("Sheet1").Cells(1, 1).Select
End Sub
This is a quick way to accomplish what you said you wanted done. It may not be the best way, but you should be able to drop it in and run with it:
Private Sub CommandButton1_Click()
Dim xls As Excel.Application
set xls = new Excel.Application
xls.Workbooks.Open "D:/power system design/foo.xlsx", ,False
xls.Visible = true
End Sub
or if you want to work with the opened workbook
Private Sub CommandButton1_Click()
Dim xls As Excel.Application
Dim wb as Excel.Workbook
set xls = new Excel.Application
set wb = xls.Workbooks.Open(Filename:="D:/power system design/foo.xlsx", ReadOnly:=False)
xls.Visible = true
End Sub
This will result in the sheet being opened in a new Excel application window.