Show data from excel table to listbox in excel sheet - excel

hello i tried to populate my listbox at my excel sheet but i had a hard time to put a right code in VBA.
as you can see in this picture the box that marked is my list box. and i have the data table in other sheet called "Data Barang" (sheet2) and i tried to show the data table to the listbox and when i double click the data at the listbox it will pull the selected data row to those text boxes above the listbox. The listbox name and the table name are same which is "DataBarang".
anyone have reference what code can work for my listbox?
there's the code i have tried
Private Sub Workbook_Open()
With Sheet1.DataBarang
.ColumnHeads = True
.ColumnCount = 14
.ListFillRange = Sheet2.ListObjects("DataBarang").Range.Select
End With
End Sub
-----------------------------------EDITED-----------------------------------
I have success to populate my listbox but it seems cannot filled the column heads. can anybody help me to fill those column heads?
here is my code that i used
Sub loaddata()
Dim listdata As Object
Set listdata = Sheet1.DataBarang
Dim tabeldata As Range
Set tabeldata = Sheet2.Range("DataBarang")
With listdata
.AutoLoad = True
.ColumnHeads = True
.ColumnCount = 14
.List = tabeldata.CurrentRegion.Value
End With
End Sub

You don't neeed to select the range - but have to pass the adress of the range as string (it always helps to read the documentation: https://learn.microsoft.com/en-us/office/vba/api/excel.controlformat.listfillrange
Private Sub Workbook_Open()
With Sheet1.DataBarang
.ColumnHeads = True
.ColumnCount = 14
.ListFillRange = Sheet2.ListObjects("DataBarang").DataBodyRange.Address(False, False, xlA1, True)
End With
End Sub

Related

Delete row function lead to run time error '-214702882 (8007000e)':

Hello I have a sheet listed as ThisWorkBook.Sheets("Dash Board") or sheet1. That sheet contain a listbox that show data table from sheet2 with name "Data Barang". I tried to create a delete row command button from shape and assigned it with the function at sheet1 where my dash board displayed, but every time I click on, it shows nothing and when I click other assigned button such as update data button (it works perfectly fine before I clicked delete button) it got an error
run time error '-214702882 (8007000e)': it says not enough memory.
this is the code that I used on my delete button in module
Sub DeleteRow(ByVal row As Long)
ThisWorkbook.Sheets("Data Barang").Range("A2").Offset(row).EntireRow.Delete
End Sub
and then I call the function and assign it to my shape
this is the code at sheet1
Sub hapus()
Call DeleteRow(Sheet1.DataBarang.ListIndex)
End Sub
can any body help me? my intention is to delete a row that I have selected in the list box that displayed data from table in other sheet (sheet2)
this is the listfillrange of my listbox
Sub loaddata()
Dim listdata As Object
Set listdata = Sheet1.DataBarang ' this is my listbox name in sheet1
Dim tabeldata As Object
Set tabeldata = Sheet2.ListObjects("DataBarang") 'this is my data table in sheet 2. it have a same name with my listbox name in sheet1
With listdata
.AutoLoad = True
.ColumnHeads = True
.ColumnCount = 12
.ListFillRange = tabeldata.DataBodyRange.Address(External:=True)
End With
End Sub
and then i recall it in this code
Private Sub Workbook_Open()
Call loaddata
Call locktextbox
End Sub
Remove the ListFillRange before you delete the row and then re-apply it.
Option Explicit
Private Sub btnDelete_Click()
Dim i As Long
i = Sheet1.DataBarang.ListIndex
With Sheet2.ListObjects("DataBarang")
If i >= 0 And .ListRows.Count > 0 Then
Sheet1.DataBarang.ListFillRange = ""
.ListRows(i + 1).Delete
Call loaddata
End If
End With
End Sub
Sub loaddata()
Dim tbl As ListObject, rng As Range
Set tbl = Sheet2.ListObjects("DataBarang")
With Sheet1.DataBarang ' ListBox
.AutoLoad = True
.ColumnHeads = True
.ColumnCount = 12
.ListFillRange = ""
If tbl.ListRows.Count = 0 Then
Set rng = tbl.Range.Rows(2)
Else
Set rng = tbl.DataBodyRange
End If
.ListFillRange = rng.Address(external:=True)
End With
End Sub

Excel VBA Userform combobox1 selection filters combobox2 based off of combobox1 selection

So I'm trying to use three Comboboxes to have a selection list for data input. I'm needing to make a selection in this order: Region -> Site -> Maintenance Plant. When a selection is made in the Region Combobox, then the Site Combobox list should filter to the options that pertain to the corresponding Region selection. Im thinking either a pivot table or vLookup needs to be used but I'm at a loss and have no clue how to get this done. Please help and thank you very much in advance.
Private Sub UserForm_Initialize()
Dim CreateBy As Range
Dim Region As Range
Dim Site As Range
Dim MaintPlant As Range
Dim Dept As Range
Dim Act As Range
Dim ImpActTyp As Range
Dim ValCat As Range
Dim ws As Worksheet
Set ws = Worksheets("LookupLists")
For Each CreateBy In ws.Range("RosterList")
With Me.CboCreateBy
.AddItem CreateBy.Value
End With
Next CreateBy
For Each Region In ws.Range("RegionList")
With Me.CboRegion
.AddItem Region.Value
End With
Next Region
For Each Site In ws.Range("SiteList")
With Me.CboSite
.AddItem Site.Value
End With
Next Site
For Each MaintPlant In ws.Range("MaintPlantList")
With Me.CboMntPlant
.AddItem MaintPlant.Value
End With
Next MaintPlant
For Each Dept In ws.Range("DeptList")
With Me.CboDept
.AddItem Dept.Value
End With
Next Dept
For Each Act In ws.Range("ActList")
With Me.CboAct
.AddItem Act.Value
End With
Next Act
For Each ImpActTyp In ws.Range("ImpActTypList")
With Me.CboImpActTyp
.AddItem ImpActTyp.Value
End With
Next ImpActTyp
For Each ValCat In ws.Range("ValCatList")
With Me.CboValCat
.AddItem ValCat.Value
End With
Next ValCat
Me.DateTextBox.Value = Format(Date, "Medium Date")
Me.PLife.Value = 0
Me.CSE.Value = 0
Me.CboRegion.SetFocus
End Sub
Get ready, because I'm about to reimagine your entire code here. I strongly recommend you create a backup of your original code module or workbook just due to the vast differences and if our ideas didn't align properly.
This will perform real-time filtering on your table, so keep this in mind using this method.
I did perform some testing on the following code, but I am human and threw this together in 20 mins or so. I wouldn't implement this in a real setting until you have fully tested the code and are comfortable with it.
And I just wanted to thank you for your use of Named Ranges. This made coding this easier.
You must enable the Microsoft Scripting Runtime library. This is used to grab the unique values from your tables. (Tools > References)
So to get things started, here is the entire code for your userform's code module:
Option Explicit
Private ws As Worksheet
Private tblLO As ListObject
Private Sub combo_region_Change()
Application.EnableEvents = False
Me.combo_maintPlant.Clear
Me.combo_site.Clear
'This is the first filter, so no worries about clearing entire AutoFilter
tblLO.AutoFilter.ShowAllData
Select Case Me.combo_region.Value
Case ""
Me.combo_site.Value = ""
Me.combo_maintPlant.Value = ""
Me.combo_site.Enabled = False
Me.combo_maintPlant.Enabled = False
Case Else
'If data is entered into first combobox, filter the table
tblLO.Range.AutoFilter 1, Me.combo_region.Value
'Populate the site combo box with new data
populateSiteCombo
'Enable the Site Combobox for user input
Me.combo_site.Enabled = True
End Select
Application.EnableEvents = True
End Sub
Private Sub combo_site_Change()
Application.EnableEvents = False
Me.combo_maintPlant.Clear
'Clear the filtering, then readd the Region's filter
tblLO.AutoFilter.ShowAllData
tblLO.Range.AutoFilter 1, Me.combo_region
Select Case Me.combo_site.Value
Case ""
Me.combo_maintPlant.Value = ""
Me.combo_maintPlant.Enabled = False
Case Else
'If data is entered into first combobox, filter the table
tblLO.Range.AutoFilter 2, Me.combo_site.Value
'Populate the Plant combo box with new data
populatePlantCombo
'Enable the Plant Combobox for user input
Me.combo_maintPlant.Enabled = True
End Select
Application.EnableEvents = True
End Sub
Private Sub populatePlantCombo()
'Grab unique values from Region column using Dictionary
Dim i As Long, regionDict As New Scripting.Dictionary
Dim arrReg() As Variant
'If it filters only 1 item, then it's just a single cell and not an arr
With ws.Range("MaintPlantList").SpecialCells(xlCellTypeVisible)
If .Count = 1 Then
Me.combo_maintPlant.AddItem .Value
Exit Sub
Else
arrReg = .Value
End If
End With
With New Scripting.Dictionary
For i = 1 To UBound(arrReg)
If Not .Exists(arrReg(i, 1)) Then
.Add arrReg(i, 1), "" 'We only add to dictionary for tracking
Me.combo_maintPlant.AddItem arrReg(i, 1)
End If
Next
End With
End Sub
Private Sub populateSiteCombo()
'Grab unique values from Region column using Dictionary
Dim i As Long, regionDict As New Scripting.Dictionary
Dim arrReg() As Variant
'If it filters only 1 item, then it's just a single cell and not an arr
With ws.Range("SiteList").SpecialCells(xlCellTypeVisible)
If .Count = 1 Then
Me.combo_site.AddItem .Value
Exit Sub
Else
arrReg = .Value
End If
End With
With New Scripting.Dictionary
For i = 1 To UBound(arrReg)
If Not .Exists(arrReg(i, 1)) Then
.Add arrReg(i, 1), "" 'We only add to dictionary for tracking
Me.combo_site.AddItem arrReg(i, 1)
End If
Next
End With
End Sub
Private Sub populateRegionCombo()
'Grab unique values from Region column using Dictionary
Dim i As Long, regionDict As New Scripting.Dictionary
Dim arrReg() As Variant
arrReg = ws.Range("RegionList").Value
With New Scripting.Dictionary
For i = 1 To UBound(arrReg)
If Not .Exists(arrReg(i, 1)) Then
.Add arrReg(i, 1), "" 'We only add to dictionary for tracking
Me.combo_region.AddItem arrReg(i, 1)
End If
Next
End With
End Sub
Private Sub UserForm_Initialize()
Set ws = ThisWorkbook.Worksheets("LookupLists") 'Module-defined var
Set tblLO = ws.ListObjects("Table1") 'Module-defined var
tblLO.AutoFilter.ShowAllData
Me.combo_maintPlant.Enabled = False
Me.combo_site.Enabled = False
'We only populate this one during init because the others
'will populate once a value is used in this box
populateRegionCombo
End Sub
If you decided to scroll down to understand what's going on here, then great.
Let's start with the initialization:
Private Sub UserForm_Initialize()
Set ws = ThisWorkbook.Worksheets("LookupLists") 'Module-defined var
Set tblLO = ws.ListObjects("Table1") 'Module-defined var
tblLO.AutoFilter.ShowAllData
Me.combo_maintPlant.Enabled = False
Me.combo_site.Enabled = False
'We only populate this one during init because the others
'will populate once a value is used in this box
populateRegionCombo
End Sub
We defined the module variables ws and tblLO. I'm not a huge fan of module-scoped variables, but we can usually get along when they are private vars to a userform module. Now the other functions in the code module can access these.
We reset autofiltering and disabled the two combo boxes that shouldn't be used until a selection is made for the region. Only after the region is selected will the next box be available for selection. We will handle these using Change Events for the comboboxes.
The userform is mostly controlled by the combo_region_change and combo_site_change events. Everytime region_change is fired, it will clear all the other combo boxes to redetermine it's new value. Then it will refilter as appropriately. The combo_site does the same, but it only clears the maintaince box. These event handlers also establish which of the other combox boxes are enabled depending on their values. So if you where to completely clear the site box for example, it will disable access to the Plant box again.
Finally you just have the "populate subs". Their jobs are simply to (re)populate the next combo box once the appropriate event handler is triggered.
Tip: If you feel the need to reset the filtering once you close your userform, you can just place the code to reset it in a UserForm_Terminate() event. It makes no difference to the above code if autofilter is enabled or not prior to it running, so that is preference only.

Unhide/Hide rows in excel with a form checkbox

I have a form created in excel which has rows [10:48] hidden and I want to make so that when you click a checkbox rows [10:48] are unhidden. I assigned a macro to the checkbox and using this formula:
Private Sub CheckBox45_Click()
If CheckBox45 = True Then
[10:48].EntireRow.Hidden = False
Else: [10:48].EntireRow.Hidden = True
End If
End Sub
When I click the checkbox nothing happen, but when I unhide the rows and click the checkbox it hides the rows. Which makes me think that only one of the actions is working. Is there a way to fix this?
Thanks in advance for the help.
Don't know if this matters but the form checkbox is in column D row 6
This assumes you are hiding/unhiding rows on Sheet 1 and the checkbox belongs to sheet 1 of the workbook, then:
Private Sub CheckBox30_Click()
If ThisWorkbook.Sheets(1).CheckBoxes("Check Box 30").Value = 1 Then
ThisWorkbook.Sheets(1).Rows("10:48").Hidden = true
Else
ThisWorkbook.Sheets(1).Rows("10:48").Hidden = false
End If
End Sub
Here is another approach.
The statement ws.CheckBoxes("Check Box 30") = 1 will either return TRUE or FALSE which will either hide, or unhide, your target rows.
Private Sub CheckBox30_Click()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Range("A10:A48").EntireRow.Hidden = ws.CheckBoxes("Check Box 30") = 1
End Sub

It is correct for hide or unhide a control by VBA in Excel 2010?

I have a sheet named "MainSheet" in a Workbook in Excel 2010.
this sheet included an activeX control named "OptionButton1". when the cell's value of "C18" is "2" then this control should be hide.
I wrote below code but does not work.
► a more question: can I have three activeX (Radio Button) related to one cell with three different value like radio button in form control?
Any advice is appreciated. :)
Sub MS_Method()
If Range("C18").Value = 2 Then
ActiveSheet.MainSheet("OptionButton1").Visible = False
ElseIf Range("C18").Value = 1 Then
ActiveSheet.MainSheet("OptionButton1").Visible = True
End If
End Sub
Assuming your ActiveX OptionButton is Named "OptionButton1", the code below (tested) will work:
Option Explicit
Sub MS_Method()
Dim Sht As Worksheet
' modify "MainSheet" to your sheet name (where you have your OptionButton)
Set Sht = ThisWorkbook.Sheets("MainSheet")
If Range("C18").Value = 2 Then
Sht.OLEObjects("OptionButton1").Visible = False
ElseIf Range("C18").Value = 1 Then
Sht.OLEObjects("OptionButton1").Visible = True
End If
End Sub

Excel: combobox and checkbox interference?

I am making an Excel form with some activeX controls and am having a problem incorporating the following functionallity:
I wish for the users to select a number in ComboBox11. If the number be 0, the form changes so, that comboboxes 9 and 10 become disabled (using VBA code) and the table below 'fades out' (using conditional formatting), informing the user not to fill it out.
On the other hand if the user selects a number larger than 0, the form stays as it is. Under the table is a checkbox (checkbox1) used to expand the table (unhiding previously hidden rows) if data needeed to be put in the form is larger than the table size.
The VBA code behind combobox 11 is:
Private Sub ComboBox11_change()
Dim ws As Worksheet
Set ws = Sheets("Form")
If Not Me.ComboBox11.Text = "" Then ws.Range("J24") = CInt(Me.ComboBox11.Text) 'to write integer instead of text into linked cell
If Me.ComboBox11.Value = 0 Then
Me.ComboBox9.Enabled = False
Me.ComboBox10.Enabled = False
If Me.CheckBox1.Value = True Then Me.CheckBox1.Value = False 'if combobox11 is 0 than the table doesn't need to be expanded
Me.CheckBox1.Enabled = False
Else
Me.ComboBox9.Enabled = True
Me.ComboBox10.Enabled = True
Me.CheckBox1.Enabled = True
End If
End Sub
And the code behind CheckBox1 is:
Private Sub CheckBox1_Change()
Dim ws As Worksheet
Set ws = Sheets("Form")
If CheckBox1.Value = False Then ws.Rows("46:71").Hidden = True
If CheckBox1.Value = True Then ws.Rows("46:71").Hidden = False
End Sub
So, if I select 0 in combobox11 the result is:
So far so good. But if I select something larger than 0, say 1 in combobox11 and then try to expand the table by clicking on the checkbox1, the table expands, but I get an error message:
Run-time error '1004': Not possible to set properties: enabled class:
OLEObject
(not sure about the exact error text, since I'm not using English MSOffice)
When pressing the Debug button, the following line in Sub ComboBox11_Change() lights up:
Me.ComboBox9.Enabled = True
The Strange thing is, that this error does not appear when the combobox11 is left blank ( a value is not selected).
I have no idea why the checkbox would interact with the other comboboxes. I am bewildered and any help would be much appreciated.
To reproduce this:
Have a sheet like this:
A1:A6 is the ListFillRange of the ComboBox.
Then hiding any row between 1:6 using VBA code in CheckBox1_Change() will throw the error.
Private Sub CheckBox1_Change()
If CheckBox1.Value = False Then Me.Rows("7:13").Hidden = True
If CheckBox1.Value = True Then Me.Rows("7:13").Hidden = False
'If CheckBox1.Value = False Then Me.Rows("6:13").Hidden = True 'ERROR
'If CheckBox1.Value = True Then Me.Rows("6:13").Hidden = False 'ERROR
End Sub
Private Sub ComboBox1_Change()
If Me.ComboBox1.Value = 0 Then
If Me.CheckBox1.Value = True Then Me.CheckBox1.Value = False
Me.CheckBox1.Enabled = False
Else
Me.CheckBox1.Enabled = True
End If
End Sub
If we create a name named "list" which is related to a whole column like this:
and use this "list" as the ListFillRange of the ComboBox, then the error occurs ever if rows in this sheet were hidden from code. This is independent on whether the hidden rows are within the real active "list" rows 1-6 or not.
If we not reference a whole column in the name but for example only rows 1-10 like:
=INDEX(Sheet1!$A$1:$A$10;1):INDEX(Sheet1!$A$1:$A$10;6)
then the error only occurs if the code hides rows from 1 to 10 but not if it hides rows from 11 upwards.
Edit:
To continue my example:
Moved the numbers from Sheet1!A:A to Sheet2!A:A and created a named range "list" related to
=Sheet2!$A$1:INDEX(Sheet2!$A$1:$A$40;COUNTIF(Sheet2!$A$1:$A$40;"<>"))
Then the following code to set Sheet1.ComboBox1.ListFillRange to "list" will work if it is within the Sheet2 class module:
Private Sub Worksheet_Change(ByVal Target As Range)
ThisWorkbook.Worksheets(1).ComboBox1.ListFillRange = "list"
End Sub
It will produce the error if setting the ListFillRange is tried from within the Sheet1 class module.
Because comments are too short to explain whad I did to solve the issue, I am posting this answer.
First of all thanks to Axel Richter, who took his time to elaborate on my problem.
The Combobox11 was filled with a generated ListFillRange in the name manager:
The described error stopped appearing, as soon as I changed the ListFillRange. At first I tried a simple alternative: "=list!AU1:AU40" Although I don't understand the problem it is now solved!
Afterwards I used the following code to create a dynamic list for combobox11.
Dim zadnji As Integer
zadnji = Sheets("Form").Range("T9").Value + 1
Me.OLEObjects("combobox11").ListFillRange = "=lists!AU1:AU" & zadnji

Resources