Excel VBA: Displaying table data using drop down list

情到浓时终转凉″ 提交于 2021-01-29 08:11:38

问题


I am a beginner in VBA. I have a worksheet in Excel where tables for each individual month is created to calculate the total amount of manhours for each month. The tables are located in different columns in the worksheet. The data in this table is populated using manually inputted data in respective sheets created for each month.

Currently, this is being done manually and the list is getting very long. I would like to improve on this by creating a dropdown list filter and retrieving the respective data from each month and year and displaying it in the form of a calendar instead. Can anyone guide me on how this can be done?

This is an example of the worksheet I want to compile:

I want it to look something like this where the data for the data will change according to the data I retrieve from the respective months. The months and years will be in the form of drop down list.

The workbook will be updated on a daily basis. The names of the worksheets involved will be named in a format like this: Jul'19, Aug'19, Sept'20, etc. There will be more worksheets created over time.


回答1:


Please, create a form and place the next code in its module:

Option Explicit

Private Sub UserForm_Initialize()
    Dim sh As Worksheet, wb As Workbook
    
    Set wb = ActiveWorkbook
    For Each sh In wb.Sheets
        Me.cbMonth.AddItem sh.Name
    Next sh
End Sub

Private Sub cbMonth_Change()
  Dim wb As Workbook, sh As Worksheet, Tbl As ListObject
  Set wb = ActiveWorkbook
  Set sh = wb.Sheets(Me.cbMonth.Value)
  Set Tbl = sh.ListObjects(1)
  arr = Tbl.Range.Value
   With Me.ListBox1
        .ColumnCount = UBound(arr, 2)
        .ColumnWidths = "40;25;22;23;22;22;22;48;40"
        .list = arr
   End With
End Sub

So, you must place a combo box named cbMonth and a list box named 'ListBox1`.

On the form Initialize event the combo box is populated with the sheets name.

On the combo box Change event the 'ListBox1` is populated with the first table range of the selected sheet name. So, in each sheet should exist only one table, or, if more tables, the necessary one must be the first.

You will also be able to input data in the list box, using its DblClick event. The user will be asked about the day where the data to be inputted and then, the sheet can be updated, too...



来源:https://stackoverflow.com/questions/65021600/excel-vba-displaying-table-data-using-drop-down-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!