Excel VBA: ListBox-UserForm Variable creation issue - vba

Checked other similar questions on other websites, but could not find a solution.
I am trying to generate variables from the contents of a listbox-userform. The contents in the list are the names of workbooks. The first piece of code shows you how I generate the contents of the list for your reference. The second piece of code is the one with the issue.
Private Sub CommandButton1_Click()
Dim wb As Workbook
For Each wb In Workbooks
With ListBox1
.AddItem (wb.Name)
End With
Next wb
lbl_Exit:
End Sub
I am getting a Object Required error on the For Each line below. This piece of code resides in the Userform.
Private Sub CommandButton3_Click()
Dim MainBook As Workbook
Dim ListBox1 As ListBox
For Each Item In ListBox1
If Item.Name Like "Aggregate" Then
Item.Select
Set MainBook = Selection
End If
Next
End Sub
Note: I read that Item is a property of a ListBox which is where I got that from.

Is this what you are trying?
Private Sub CommandButton1_Click()
Dim wb As Workbook
For Each wb In Workbooks
With ListBox1
.AddItem (wb.Name)
End With
Next wb
End Sub
Private Sub CommandButton2_Click()
Dim MainBook As Workbook, i as Long
For i = 0 To (ListBox1.ListCount -1)
If ListBox1.List(i) Like "Aggregate" Then
Set MainBook = Workbooks(ListBox1.List(i))
MainBook.Activate
Exit For
End If
Next
End Sub

Related

How to make Excel print selective tabs using VBA?

I already coded my Excel workbook to print out all of my selective sheets that I need all at once. However, there are times where I will only need it to print specific sheets instead of all of them. Is there a way that before I print I can have my code ask me what range of sheets I want to print so I am not getting all 45 when I just need 7? Thank you in advance.
Chris
Sub PrintWorksheets()
Application.ScreenUpdating = False
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Feedback Data" Then
If ws.Visible = xlSheetVisible Then
ws.PrintOut
End If
End If
Next ws
Application.ScreenUpdating = True
MsgBox "All charts have been printed Mark"
End Sub
Here's an example of a UserForm where we populate a ListBox with the names of all sheets in the file:
Code behind the UserForm:
Dim i As Long
Private Sub UserForm_Initialize()
For i = 1 To ActiveWorkbook.Sheets.Count
ListBox1.AddItem ActiveWorkbook.Sheets(i).Name
Next i
End Sub
Private Sub btnPrint_Click()
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then
ActiveWorkbook.Worksheets(ListBox1.List(i)).PrintOut
End If
Next i
End Sub
Private Sub btnCancel_Click()
Unload Me
End Sub
Naturally, there are other facets to this, such as changing the ListBox's MultiSelect property to 1 (to allow multiple sheets to be selected), and in my example I rename my buttons out of practice. But this is how you would solve your problem, in theory.
You could try to create more subroutines, each having different predefined set of sheets to select. Examples:
Public Sub selectSheets_1()
Dim arrayOfNames As Variant
arrayOfNames = Array(ws1.Name, ws2.Name, ws4.Name)
ThisWorkbook.Sheets(arrayOfNames).Select
End Sub
Public Sub selectSheets_2()
Dim arrayOfNames As Variant
arrayOfNames = Array(ws8.Name, ws15.Name, ws25.Name, ws35.Name, ws45.Name)
ThisWorkbook.Sheets(arrayOfNames).Select
End Sub
And so on...
Where ws# is the codename of sheet.

VBA Name a Sheet with ComboBox

I have a commandButton which opens a UserForm to add a new Worksheet.
In this Userform is a ComboBox, where i can choose the machine type.
Now i want to create a new Worksheet with the Name of the machine type which was selected in the ComboBox.
This is my Code:
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Sheets("Sheet1").Copy Before:=Sheets(10)
ws.Name = ComboBox1
[UserForm1].Hide
End Sub
Private Sub UserForm_Initialize()
ComboBox1.List = Array("Machine Type 1", "Machine Type 2")
End Sub
Is there a way to create a new sheet, which is a copy from Sheet1 and name it like the machine type from the ComboBox1?
Thanks for your help.
Try the code below, see notes in the code's comments:
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Sheets("Sheet1").Copy Before:=Sheets(10)
Set ws = ActiveSheet ' <-- you need to set the worksheet object to the latest copied sheet
ws.Name = ComboBox1.Value '<-- now you can modify the name using the worksheet object
Me.Hide '<-- hide the user-form
End Sub
use
Private Sub CommandButton1_Click()
Sheets("Sheet1").Copy Before:=Sheets(Sheets.Count)
ActiveSheet.Name = ComboBox1.Value
Me.Hide
End Sub

Automatically open an excel file to cell A1 in all worksheets (using VBA)

I am trying to write VBA code so that whenever I open any file in excel, it automatically goes to Cell A1 in all sheets (no matter what cells were selected when it was last saved). I found something online that suggested putting the following code in my Personal .xlsb project:
Sub kTest()
Dim i As Long, s() As String, a As String, n As Long
With ActiveWorkbook
For i = 1 To .Worksheets.Count
a = a & .Worksheets(i).Name
n = n + 1
ReDim Preserve s(1 To n)
s(n) = .Worksheets(i).Name
If Len(a) > 224 Then
.Worksheets(s).Select
.Worksheets(s(1)).Activate
[a1].Select
n = 0: a = "": Erase s
End If
Next
If Len(a) Then
.Worksheets(s).Select
.Worksheets(s(1)).Activate
[a1].Select
End If
Application.Goto .Worksheets(1).Range("a1")
End With
End Sub
But nothing happens when I open a file. Please help!
You cannot go to Cell A1 in every sheet. But if you would like to go to Cell A1 of a single sheet you could do the following.
Create a class ExcelEvents with the following code
Option Explicit
Private WithEvents App As Application
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
App.Goto Wb.Worksheets(1).Range("A1")
End Sub
Private Sub Class_Initialize()
Set App = Application
End Sub
And in ThisWorkbook add
Option Explicit
Private xlApp As ExcelEvents
Private Sub Workbook_Open()
Set xlApp = New ExcelEvents
End Sub
Save the workbook, re-open it and the code in the workbook_open event will run and that means as soon as you open another workbook the code will goto cell A1 of sheet 1
EDIT If you really mean to select A1 in every single sheet you could change the code as follows
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
Dim sh As Worksheet
App.ScreenUpdating = False
For Each sh In Wb.Worksheets
sh.Select
sh.Range("A1").Select
Next
App.Goto Wb.Worksheets(1).Range("A1")
App.ScreenUpdating = True
End Sub
A simple solution:
For Each Sheet In ActiveWorkbook.Worksheets
Sheet.Select
Range("A1").Select
Next
Using MicScoPau's loop through the worksheets
Place the following code in the ThisWorkbook module of Personal.xlsb:
You'll have to reopen excel for this to work the first time.
If your Personal.xlsb is hidden, then you will have some issues with the each sheet in activeworkbook.
Private WithEvents app As Application
Private Sub app_WorkbookOpen(ByVal Wb As Workbook)
For Each Sheet In ActiveWorkbook.Worksheets
Sheet.Select
Range("A1").Select
Next
End Sub
Private Sub Workbook_Open()
Set app = Application
End Sub

In Excel, how can I set up a VBA ComboBox so that it still works if the worksheet is copied?

In Excel 2010, I can create an ActiveX ComboBox in a worksheet and configure it to give me a list of all worksheets, and it will activate whichever worksheet I select.
However, if I copy the worksheet containing the ComboBox, the new ComboBox is dead. I have to duplicate all the VBA code that makes it work, changing the labels accordingly.
Is there any way to set it up so that it works automatically if I copy the worksheet?
This is how I'm currently doing it:
Microsoft Excel Objects \ ThisWorkbook:
Private Sub Workbook_Open()
' Rebuild the list of sheets for the worksheet ComboBox.
Dim i As Long
For i = 1 To ThisWorkbook.Sheets.Count
Sheet1.ComboBox1.AddItem Sheets(i).Name
Next
End Sub
Microsoft Excel Objects \ Sheet1(Sheet1):
Private Sub ComboBox1_Change()
With Sheet1.ComboBox1
Sheets(.List(.ListIndex)).Activate
End With
End Sub
Do this in your Workbook Module:
Private Sub Workbook_Open()
Call PopulateBoxes(Sheet1)
End Sub
In a standard module, do this:
Sub PopulateBoxes(ws As Worksheet)
Dim sht As Worksheet
'Populate the combobox on sheet 1
Dim obj
Set obj = ws.OLEObjects.Item("ComboBox1").Object
obj.Clear
For Each sht In ThisWorkbook.Worksheets
obj.AddItem sht.Name
Next
End Sub
Then, in your Sheet1 module, make this:
Private Sub ComboBox1_Change()
With Me.ComboBox1
Sheets(.List(.ListIndex)).Activate
End With
End Sub
Private Sub WOrksheet_Activate()
Call PopulateBoxes(Me)
End Sub
Now, the code for each ComboBox should be functional even after copying sheets.

Macro to copy and/or move selected sheets to a new workbook

Can someone please help me with a macro? I want to move and/or copy a few selected sheets (hidden & visible) to a new workbook, but since I have a few workbooks open at a time, I want to be able to select worksheets in all open workbooks from like a drop down menu and move and/or copy to a new workbook. I want to move some and copy some worksheets so will need both options in selection box.
Please help as I have cracked my head on it and got nowhere.
I have tried the below:
Sub CopySheet()
Dim i As Integer, x As Integer
Dim shtname As String
'i = Application.InputBox("Copy how many times?", "Copy sheet", Type:=1)
'For x = 0 To i - 1
ActiveSheet.Copy After:=Sheets(Sheets.Count)
shtname = InputBox("What's the new sheet name?", "Sheet name?")
ActiveSheet.Name = shtname
'Next x
End Sub
But this will mean I have to type every sheet name every time.
Adam: While I try to run your code, it gives me an error - variable not specified in row Private Sub btnSubmit_Click()
How do I overcome it?
I still can't get it right Adam. I am very new to Macros and I may be doing something wrong with interpreting your instructions. Can you please suggest something like all included in one and run?
Where exactly in the original codes do I need to paste this code
Private Sub btnSubmit_Click()
End Sub
This code should get you going. It is all of the code-behind for a UserForm with two listboxes, a checkbox, and a command button for submit. The dropdowns are populated automatically depending on what workbooks are open and what worksheets these workbooks contain. It also has the option to move or copy the selected worksheet. However, you still will need to add the functionality for copying the sheet multiple times, but that will just be a loop, and shouldn't be too difficult.
'All of this code goes in the section which appears when you right click
'the form and select "View Code"
Option Explicit
Public Sub OpenWorksheetSelect()
Dim WorksheetSelector As New frmWorksheetSelect
WorksheetSelector.Show
End Sub
Private Sub lstWorkbooks_Change()
FillWorksheetList
End Sub
Private Sub UserForm_Initialize()
FillWorkbookList
End Sub
Sub FillWorkbookList()
'Add each workbook to the drop down
Dim CurrentWorkbook As Workbook
For Each CurrentWorkbook In Workbooks
lstWorkbooks.AddItem CurrentWorkbook.Name
Next CurrentWorkbook
End Sub
Sub FillWorksheetList()
Dim WorkbookName As String
WorkbookName = lstWorkbooks.Text
If Len(WorkbookName) > 0 Then
Dim CurrentWorksheet As Worksheet
For Each CurrentWorksheet In Workbooks(WorkbookName).Sheets
lstWorksheets.AddItem CurrentWorksheet.Name
Next CurrentWorksheet
End If
End Sub
Private Sub btnSubmit_Click()
Dim WorkbookName As String, WorksheetName As String
WorkbookName = lstWorkbooks.Text
WorksheetName = lstWorksheets.Text
If Len(WorkbookName) > 0 And Len(WorksheetName) > 0 Then
If chkCopy = True Then
Workbooks(WorkbookName).Sheets(WorksheetName).Copy Before:=Workbooks.Add.Sheets(1)
Else
Workbooks(WorkbookName).Sheets(WorksheetName).Move Before:=Workbooks.Add.Sheets(1)
End If
End If
Unload Me
End Sub