Set Workbook Variable from Userform Combobox - excel

I am creating a macro for my co-workers. They get a file daily and at the end of the day have to copy certain information to another workbook. The macro is to take care of the copying. I want to have a userform with a combobox popup that contains a list of current open workbooks so it knows which file to copy from. How do I set it up so that the selection made there sets a workbook variable with that selection?
What I'm trying to do is:
Sub CopySub()
Dim wb As Workbook
UserForm1.Show
Set wb = Workbooks(ComboBox1.Value)
....Rest of Copy and Paste Code
Below is the code for the userform:
Private Sub OK_Click()
'Take user selection and continue copy and paste code
UserForm1.Hide
End Sub
Private Sub Cancel_Click()
'Cancel everything, end all code
End
End Sub
Private Sub UserForm_Activate()
'Populate list box with names of open workbooks.
Dim wb As Workbook
For Each wb In Workbooks
ComboBox1.AddItem wb.Name
Next wb
End Sub

Your code isn't working now because CopySub doesn't know what\where ComboBox1 is. Also, if the user clicks the form's X to close it instead of pressing the cancel button or clicks the OK button without selecting a workbook, CopySub will keep running.
There are a couple different ways to get the form information. The simplest with your current code is to properly reference ComboBox1 and add a simple test.
Sub CopySub()
Dim wb As Workbook
UserForm1.Show
If UserForm1.ComboBox1.Value = "" Then
Exit Sub
End If
Set wb = Workbooks(UserForm1.ComboBox1.Value)
' rest of code goes here
End Sub
Something else to think about though is ways to make your macro quicker and easier to run. If the only thing on your form is a Combobox for selecting the workbook and users will be starting the macro from a keyboard-shortcut or from the menu, consider having the macro ask if they want to run the macro on the active workbook. Clicking Yes to a question is a lot faster than having to click a dropdown box, select the workbook, and then click OK.
Sub CopySub()
Dim wb As Workbook
If MsgBox("Do you want to run the macro on '" & ActiveWorkbook.Name & "'?", vbQuestion + vbYesNo) = vbYes Then
Set wb = ActiveWorkbook
Else
UserForm1.Show
If UserForm1.ComboBox1.Value = "" Then
Exit Sub
End If
Set wb = Workbooks(UserForm1.ComboBox1.Value)
End If
' rest of code goes here
End Sub

After further searching I found the answer, and its the same as what mischab points out, I didn't create a global variable so there was no way for my userform to communicate with the subroutine. I solved this by declaring a variable with scope for the whole workbook as such:
Public wb1 As String
Sub CopySub()
Dim wbCAR As Workbook
UserForm1.Show
Set wbCAR = Workbooks(wb1)
....Rest of code
and by setting the userform code to such:
Private Sub OK_Click()
wb1 = ComboBox1.Value
UserForm1.Hide
End Sub
Private Sub Cancel_Click()
Unload Me
End
End Sub
Private Sub UserForm_Activate()
'Populate list box with names of open workbooks.
Dim wb As Workbook
For Each wb In Workbooks
ComboBox1.AddItem wb.Name
Next wb
End Sub

Related

How to Make Destination Workbook Dynamic When Moving Data From Another User Selected File Using A VBA Macro in Excel

I'm attempting to have a user select a file, then through a UserForm select the worksheet they want to copy from.
The issue is on this line: ReportWbk.Sheets(ws).Cells.Copy Destination:=TargetWbk.Sheets("Test Import").Cells(1, 1)
I have confirmed that the file, worksheet selection, and copy function all work as expected. I get a run-time error '9': Subscript out of range. which to me means that the code is looking for the destination sheet in the workbook that the user selected (the 'target' file). Since it doesn't exist there, it errors out.
I'm wondering how to fix this dynamically so that the code will work without naming the workbook specifically. I might run this with other workbooks open and in different workbooks.
I verified that workbooks("WorkbookName").Sheets("Test Import").Cells(1, 1) works as I want but I'm looking to make the "WorkbookName" part dynamic / automatically select the workbook that the macro was run from.
The main code is directly below and the userform code is below that in case that's part of the issue:
Private Sub GetRange()
Dim ReportWbk As Workbook 'workbook with report data
Dim Report As Integer 'name of file with report data
Dim FD As FileDialog
Dim TargetWbk As Workbook 'this workbook
Dim ws As Variant
Set TargetWbk = ThisWorkbook
Set FD = Application.FileDialog(msoFileDialogFilePicker)
Report = FD.Show
'cancel pressed
If Report <> -1 Then Exit Sub
'open selected workbook
Set ReportWbk = Workbooks.Open(FD.SelectedItems(1))
ws = SelectSheet.Selection(ReportWbk)
'cancel pressed
If ws = vbCancel Then GoTo exitsub
ReportWbk.Sheets(ws).Cells.Copy Destination:=TargetWbk.Sheets("Test Import").Cells(1, 1)
exitsub:
ReportWbk.Close False
'changes the color of the destination worksheet tab
Worksheets("Test Import").Tab.Color = RGB(25, 25, 25)
End Sub
UserForm Code:
Private Sub cmdOK_Click()
Me.Tag = Me.ListBox1.Value
Me.Hide
End Sub
Private Sub cmdCancel_Click()
Me.Tag = vbCancel
Me.Hide
End Sub
Function Selection(ByVal wb As Object) As Variant
Dim ws As Worksheet
For Each ws In wb.Worksheets
'add all sheets to listbox
Me.ListBox1.AddItem ws.Name
Next ws
'default - select first sheet in list
With Me.ListBox1
.ListIndex = 0
.MultiSelect = fmMultiSelectSingle
End With
Me.Show
'return result
Selection = Me.Tag
Unload Me
End Function
Private Sub UserForm_Initialize()
Me.Caption = "Select Sheet"
Me.CmdOK.Caption = "OK"
Me.cmdCancel.Caption = "Cancel"
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
'disable X closing form
Cancel = CBool(CloseMode = 0)
If Cancel = -1 Then Me.Tag = vbCancel: Me.Hide
End Sub
I know this is a simple thing but I've been away from VBA for a few years and rusty as heck. Many thanks in advance!

How do I amend this VBA so it runs when a specific worksheet is selected?

I have this VBA written. Essentially what it does is; I've used 'Define Range' ("Test") on a few cells in a worksheet. The VBA makes sure that whenever the workbook is opened, it automatically zooms in to fit that range. Right now, I think it only triggers when the workbook is opened, and it gives an error message if that worksheet is not selected when the workbook is opened. Now, I would like it to run only if the specific worksheet is selected. I've literally copied it from someone else so don't really know how I would amend this...
Thanks in advance!
Private Sub Workbook_Open()
Range("Test").Select
ActiveWindow.Zoom = True
Cells(1, 1).Select
End Sub
Zoom & Scroll To Cell When Worksheet Is Activated...
... and if the worksheet is active when the workbook is opened.
It is assumed that the range is of Workbook scope.
ThisWorkbook Module
Option Explicit
Private Sub Workbook_Open()
Const WorksheetName As String = "Sheet1"
If ActiveSheet.Name = WorksheetName Then SelectMyRange
End Sub
Sheet Module, e.g. Sheet1...
... where Sheet1 is the code name i.e. the name not in parentheses, e.g. Sheet1(Data), seen in the VBE Project Explorer window.
Option Explicit
Private Sub Worksheet_Activate()
SelectMyRange
End Sub
Standard Module, e.g. Module1...
... created by using Insert Module.
Option Explicit
Sub SelectMyRange()
Const RangeName As String = "Test"
With Range(RangeName)
.Select
ActiveWindow.Zoom = True
Application.Goto .Cells(1), True
End With
End Sub

Open and close UserForm multiple times without showing it's workbook

I've created a workbook that only shows a UserForm when it runs with the following code
Private Sub Workbook_Open()
Application.Visible = False
UserForm1.Show
End Sub
When the UserForm is initialized, it opens another workbook (WHITEBOOK.xls). After data has been entered into the form and the user clicks the Submit button, the data is inserted into this workbook that has been opened (I've omitted that code, but it works)
Private Sub UserForm_Initialize()
Set wb = Workbooks.Open("S:\!Data Tracking\WHITEBOOK.xls")
wb.Sheets("Jobs with Correct Template").Activate
If IsEmpty(wb.Worksheets("Jobs with Correct Template").Range("A3").Value) = True Then
Set SheetNameCellRange = wb.Worksheets("Jobs with Correct Template").Range("A2")
Else
wb.Worksheets("Jobs with Correct Template").Activate
Set SheetNameCellRange = wb.Worksheets("Jobs with Correct Template").Range("A2", Range("A2").End(xlDown))
End If
End Sub
When the user closes the UserForm, I close the form with this code, and close the UserForm's workbook also.
Private Sub UserForm_Terminate()
Unload Me
For Each wb In Application.Workbooks
If (StrComp(wb.Name, "Whitebook Data Entry (Final).xlsm", vbTextCompare) = 0) Then
wb.Close
End If
Next
End Sub
The problem I'm having is that I can't open the UserForm if the WHITEBOOK.xls workbook is already opened. I get a Run-time error '9': Subscript out of range and it fails at this line of the UserForm_Initialize() Sub.
wb.Sheets("Jobs with Correct Template").Activate
I've tried adding a conditional when I open the WHITEBOOK workbook to check if it is already open, and if so, to make it active, but I keep running into the same issue.
The code I used to test if the workbook is open was
Private Sub UserForm_Initialize()
Dim wkb As Workbook
On Error Resume Next
Set wkb = Application.Workbooks("S:\!Data Tracking\WHITEBOOK.xls")
If wkb Is Nothing Then
Set wb = Workbooks.Open("S:\!Data Tracking\WHITEBOOK.xls")
Else
wb.Sheets("Jobs with Correct Template").Activate
End If

Prompt to close on new sheet from pivot table

I often find that with pivot tables i end up with tons of worksheets from new sheets being created via pivot table drill downs. I thought a great macro would be to display a small userform in the upper right corner of all new sheets created from pivot tables allowing the user to easily delete the sheet and return to the pivot table. However, I cant figure out how to trigger the macro. Any ideas? Basically the macro would need to be automatically triggered anytime a new sheet is created from drilling down in a pivot table.
With out getting too complex, you are probably looking for something like this...
Under "ThisWorkbook" add the following code:
EDITED
This was working for me:
Private Sub Workbook_NewSheet(ByVal Sh As Object)
If Detect_Pivot(Sh) Then
Sh.Activate
frmSheetOptions.Show
End If
End Sub
Function Detect_Pivot(wsNew As Worksheet) As Boolean
Dim wb As Workbook
Dim pvt As PivotTable
Dim bNew As Boolean
Dim i As Integer
i = 0
bNew = True
Set wb = ThisWorkbook
For Each pvt In wsNew.PivotTables
i = i + 1
s = Split(pvt.SourceData, "!")
sName = s(0)
If wsNew.Name = sName Then
bNew = False
Exit For
End If
Next
If i > 0 Then Detect_Pivot = bNew
End Function
Inside the frm you want to display:
Private Sub cmdHide_Click()
frmSheetOptions.Hide
End Sub
Private Sub cmdDelete_Click()
ActiveSheet.Delete
frmSheetOptions.Hide
End Sub
Private Sub UserForm_Initialize()
frmSheetOptions.lblSheetName = ActiveSheet.Name
End Sub
To start an event whenever a new sheet is created, you can use the following example (an answer from Tim Williams). However, I'm not sure how to tell if the new sheet was created from a pivot table. The drill-down might be an event triggered by the pivot table, in which case, maybe you can apply this method to find it. It would take some investigation.
Private WithEvents app As Excel.Application
Sub Init()
Set app = Application 'start capturing events
End Sub
Private Sub app_NewWorkbook(ByVal Wb As Workbook)
Debug.Print "New"
End Sub
Private Sub app_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean)
Debug.Print "Before close: " & Wb.Name
End Sub
Private Sub app_WorkbookOpen(ByVal Wb As Workbook)
Debug.Print "Open: " & Wb.Name
End Sub

excel 2007 Workbook_open not working

I am trying to clear Print Area And Autofilter when excel opens:
Am total novice in Excel vba so Assmebled the followingcode from googling around
This code I have put in ThisWorkbook of Personal.xlsb in the XLstart folder and ofcourse the macro security has been set to enable all macros
Option Explicit
Public WithEvents xlApp As Excel.Application
Private Sub Workbook_Open()
Set xlApp = Application
End Sub
Private Sub Workbook_Close()
Set xlApp = Nothing
End Sub
Private Sub xlApp_WorkbookOpen(ByVal Wb As Workbook)
Application.EnableEvents = False
Call ClrPrntArea
Application.EnableEvents = True
End Sub
Here is the ClrPrntArea
Sub ClrPrntArea()
Dim ws As Object
For i = 1 To ActiveWorkbook.Worksheets.count
With Worksheets(i)
.PageSetup.PrintArea = ""
.PageSetup.FitToPagesWide = 1
End With
Next
End Sub
I will also be putting another macro call to module in personal xlsb for resetting the autofiter once above starts working..Any inputs will be really helpfull
in PERSONAL.xlsb, module ThisWorkbook, try the below; it's nearly the same code as in your request, with some modif's:
application object declared Private
event routine uses the local WB object variable handed over as parameter, instead of the ActiveWorkbook object
replaced For ... Next by For Each ... Next and working with local object variables
trap processing of PERSONAL.xlsb itself
Once you're happy remove all the MsgBox statements (and the Else), they are just to show what is happening and when.
Private WithEvents Excel_App As Excel.Application
' runs when Excel_App encounters a Workbook_Open() event
Private Sub Excel_App_WorkbookOpen(ByVal WB As Workbook)
Dim WS As Worksheet
If WB.Name <> "PERSONAL.xlsb" Then
MsgBox "PERSONAL.xlsb: Excel_App_WorkbookOpen(): " & WB.Name
For Each WS In WB.Worksheets
WS.PageSetup.PrintArea = ""
WS.PageSetup.FitToPagesWide = 1
If WS.FilterMode Then
WS.ShowAllData
End If
Next
Else
MsgBox "PERSONAL.xlsb: Excel_App_WorkbookOpen(): myself"
End If
End Sub
' runs when PERSONAL.xlsb is opened
' assign current Excel application to object variable Excel_App
Private Sub Workbook_Open()
MsgBox "PERSONAL.xlsb: Workbook_Open()"
Set Excel_App = Application
End Sub
Note:
When the event handler doesn't start when you double-click an Excel file (e.g. on your desktop), close all Excel applications and inspect the task manager for additional orphaned Excel processes which need to be killed. It happened to me while playing around with this code

Resources