Listview vba excel как

by Igor Katenov, the lead developer at 10Tec

The native ListView control from the OS Windows is a control allowing you to display items in various layouts. This versatile control can be used in Microsoft Office VBA. In this article you will find some Excel VBA ListView control examples with our analysis of their drawbacks and serious problems.

Adding the ListView control in VBA

Before you can add ListView control in VBA, you need to have the MS Windows common controls pack (MSCOMCTL.OCX) installed and registered in your system. If MSCOMCTL.OCX is registered properly, you can add the ListView control in Excel VBA using the Additional Controls dialog:

Adding ListView control in Excel VBA

Pay attention to the location of MSCOMCTL.OCX in the Additional Controls dialog. This OCX is a 32-bit executable file, and it must be placed in the SysWoW64 system directory but not in System32 in 64-bit versions of Windows. For more info, read the following StackOverflow post:

ListView Common Control (mscomctl.ocx) not installed under Excel 2016 / Windows10

As you can also conclude after reading this post, the ListView control may be absent in the latest version of Microsoft Office and Windows. Fortunately for all us, we can still download the Microsoft Visual Basic 6.0 Common Controls redistributable package including ListView from this page on Microsoft’s website.

Many developers experienced problems with instantiating common controls like ListView on Excel worksheets after recent updates in the Windows and Office products even if the Windows common controls OCX was registered correctly. To avoid these issues in production code executing on the computers of your clients, you can try to Create ListView in VBA at Runtime. The essential part of the suggested code solution looks like the following:

' Create a ListView control in VBA code
Dim objListView As ListView
Set objListView = ThisWorkbook.Sheets(1).OLEObjects.Add( _
   ClassType:="MSComctlLib.ListViewCtrl.2", _
   Link:=False, DisplayAsIcon:=False, _
   Left:=50, Top:=50, Width:=200, Height:=100).Object

' Set ListView properties through the objListView reference
objListView.LabelEdit = lvwAutomatic
objListView.CheckBoxes = True

One important thing related to this code and any other code manipulating the ListView control in Excel VBA is the following. To use the specific ListView control types and properties in VBA code (like the ListView type itself, the LabelEdit and CheckBoxes properties, the lvwAutomatic named constant and the like), you need to add the reference to the MSComctlLib type library implemented in the same MSCOMCTL.OCX file to your Excel VBA project. If you do not do this, Excel VBA will highlight every member related to ListView with the message «Compile error: User-defined type not defined».

To add a reference to the MSComctlLib type library in your Excel VBA project, use the ToolsReferences dialog in Excel VBA:

Add MSComctlLib to Excel VBA for ListView types

If you do not find the «Microsoft Windows Common Controls 6.0 (SP6)» record in the list of available controls (which may be the case if you have never used common controls like ListView in Excel VBA), press the Browse button to select the MSCOMCTL.OCX file on your hard drive. Generally you will find it in the Windows System directory (System32 or SysWoW64 depending on the edition of your Windows).

Opening the References dialog in Excel VBA may fail with the «Error accessing the system registry» message in the latest versions of Windows like Windows 7 or Windows 10. If you see this, you need to relaunch the Microsoft Excel application with administrator rights to grant this application full access to the Windows registry for operations with COM type libraries.

Edit subitems in ListView in Excel VBA

The ListView control provides you with the in-place editing capability to edit item labels. However, if your ListView control works in the report (details) view to imitate a grid control, there is no built-in tool to edit ListView subitems.

You can find a lot of Visual Basic examples of how to implement editing for ListView subtitems in the Internet. All these solutions are based on the same idea: you need to add an additional text box control to your form containing the editable ListView control and place this extra text box over the required subitem when the user is going to edit it.

If try to go this way to implement editable ListView in Excel VBA, you will face two serious troubles related to this development environment. First, the vast majority of published solutions imply that you deal with pixel coordinates everywhere. But control positions and sizes in UserForms are measured in points, so you will need to convert them from points to pixels with helper functions based on the Windows API GetDeviceCaps call (see, for example, this link).

The other problem is that you cannot place the VBA TextBox control from the Microsoft Forms 2.0 package over the ListView control in VBA. Even if you can make this construction work with another text box control, think about reusing of this solution for all ListView controls in which you need subitems editing. You will duplicate the ListView editing infrastructure code and this external editor for all these ListView controls. Your Excel VBA solution will be bloated, and it will be very hard to support it.

Checkboxes in ListView subitems

«Add checkboxes in subitems of listview» is a popular Internet search query related to the ListView control. As a rule, people are searching for a solution to this problem when they use ListView in report mode and want to add checkboxes into several ListView columns.

Unfortunately, the best thing you can do using the native ListView features is to place checkboxes only into one column:

ListView with checkbox column in UserForm

You can easily enable checkboxes for ListView items from VBA code by setting the CheckBoxes property of the ListView control to True, but this adds native checkbox controls only to the item labels in the very first column. If you need checkboxes only in one column displayed not on the first place, you can use a simple trick and move the columns with item labels to the required position. The screenshot with the ListView control on a UserForm above was captured after we had launched the form with the following initialization code, which is an example of how to add ListView subitems in Excel VBA:

With ListView1
   .View = lvwReport
   .CheckBoxes = True
   .FullRowSelect = True
   .Gridlines = True
   With .ColumnHeaders
      .Clear
      .Add , , "Item", 70
      .Add , , "Subitem-1", 70
      .Add , , "Subitem-2", 70
   End With
    
   Dim li As ListItem
    
   Set li = .ListItems.Add()
   li.ListSubItems.Add , , "Subitem 1.1"
   li.ListSubItems.Add , , "Subitem 1.2"
    
   Set li = .ListItems.Add()
   li.ListSubItems.Add , , "Subitem 2.1"
   li.ListSubItems.Add , , "Subitem 2.2"
   
   Set li = .ListItems.Add()
   li.ListSubItems.Add , , "Subitem 3.1"
   li.ListSubItems.Add , , "Subitem 3.2"
    
   .ColumnHeaders(1).Position = 2
End With

However, this approach does not work if you need checkboxes in ListView subitems in several columns. An excellent idea how you can imitate real checkbox controls in ListView subitems was discussed on VBForums in this thread:

http://www.vbforums.com/showthread.php?562763-How-to-add-checkboxes-in-subitem-of-listview

The idea is to use a picture of checkbox and display it in the required subitems. Fortunately, ListView allows us to easily add pictures to its subitems in the ListSubItems.Add method with its optional fourth parameter named ReportIcon. The checkbox image can be stored in the ImageList control from the aforementioned Windows common controls pack available for using on UserForms in Excel VBA as well. Below is one more Excel VBA code sample for the ListView control in which we show how to add images to ListView subitems:

With ListView1
   .View = lvwReport
   .Gridlines = True
   .SmallIcons = ImageList1
   
   With .ColumnHeaders
      .Clear
      .Add , , "Item", 40
      .Add , , "Subitem-1", 55
      .Add , , "Subitem-2", 55
      .Add , , "Subitem-3", 55
      .Add , , "Subitem-4", 55
   End With
    
   Dim li As ListItem
    
   Set li = .ListItems.Add(, , "Item 1")
   li.ListSubItems.Add , , "Subitem 1.1"
   li.ListSubItems.Add , , , 1
   li.ListSubItems.Add , , , 1
   li.ListSubItems.Add , , "Subitem 1.4"
    
   Set li = .ListItems.Add(, , "Item 2")
   li.ListSubItems.Add , , "Subitem 2.1"
   li.ListSubItems.Add , , , 2
   li.ListSubItems.Add , , , 1
   li.ListSubItems.Add , , "Subitem 2.4"
   
   Set li = .ListItems.Add(, , "Item 3")
   li.ListSubItems.Add , , "Subitem 3.1"
   li.ListSubItems.Add , , , 1
   li.ListSubItems.Add , , , 2
   li.ListSubItems.Add , , "Subitem 3.2"
End With

Checkboxes in ListView subitems in Excel VBA

This is a neat solution to display Boolean values as checkboxes in ListView columns. But if you need to provide your users with the ability to change the statuses of the ListView checkboxes interactively by clicking them, you will need to write a lot of code to support this infrastructure and duplicate it together with the ImageList control storing the checked and unchecked checkbox images for every required ListView control in your Excel VBA project.

Conclusion

We examined several common usage examples for the ListView control in Excel VBA and saw that we may encounter troubles even in all these ordinary scenarios. We tried to provide solutions or workarounds if they are possible, but an alternative way could be using our iGrid ActiveX grid in Excel VBA for ListView in report view. You will never face any of the problems mentioned above with 10Tec’s iGrid in Excel VBA and will get much more benefits, like built-in grouping/sorting, in-place editing of cells with the text and checkbox editors, fast flicker-free drawing code and dynamic cell formatting. Explore the product pages and articles on this website to find out more about 10Tec’s Excel VBA ListView control alternative. You can start reading from the following article:

Excel VBA Grid Control »

Содержание

  1. Listview control in excel vba
  2. Excel VBA ListView Control Examples
  3. Adding the ListView control in VBA
  4. Edit subitems in ListView in Excel VBA
  5. Checkboxes in ListView subitems
  6. Conclusion

Listview control in excel vba

The ‘records’ in a Listview are called ‘ListItems’ in VBA.
A ListView is a collection of ListItems.
The ‘fields’ of the records are called ‘ListSubItems’ in VBA.
Every record is a collection of ListSubItems.
To add a record you use: .ListItems.Add
The first ListItem has index number 1.

The method ‘ListItems.Add’ has 5 arguments

— the unique key for the record; optional
— the text/caption of the record; optional
— the linked icon; optional
— the linked small icon; optional

Each key of a ListItem must be unique.
If you do not use keys you can add as many identical ListItems as you wish.
In that case the index number is the exclusive identifier.

There is no method to check the existence of a Listitem’s key (like .exists in a Dictionary).

To add a field (ListSubitem) in a record (Listitem) use .ListSubItems.Add
The first ListSubItem gets index number 1.
The method ‘ListSubItems.Add’ has 5 arguments

Each key of a ListSubItem in a record must be unique.
If you do not use keys you can add as many identical ListSubItems as you wish.
In that case the index number is the exclusive identifier.

There is no method to check the existence of a ListSubItem’s key (like .exists in a Dictionary).

In a lot of cases you want to fill the ListView by worksheet data.
If you take the first worksheet row as columnheaders:

Next
.HideColumnHeaders = False

For j = 2 To UBound(sn)

If the worksheet contains a ListObject (‘Table’) you can use:

sp = Sheet1.ListObjects(1).HeaderRowRange
sn = Sheet1.ListObjects(1).DataBodyRange

Next
.HideColumnHeaders = False

For j = 2 To UBound(sn)

The ListView has no property to return the number of records in the ListView.
You can use the collection of ListItems.

Each ListItem has properties such as e.g.:

The ListItem’s adaptable properties:

Each ListSubItem has properties such as e.g.:

The ListSubItem adaptable properties:

You can assign a key to every ListItem.
You can also assign a key to every ListSubItem.

Use these 2 keys to read every single ListSubItem in the ListView.

You can assign a key to every ListItem.
You can also assign a key to every ListSubItem.

Use these 2 keys to adapt any single ListSubItem in the ListView. Change a ListSubItem by adapting its property .Text.

You can delete a ListItem using de method .Remove.
The argument ‘index’ indicates which ListItem should be deleted.
The first ListItem has index number 1

The method .Clear deletes all ListItems in the ListView.

You can delete a ListSubItem using the method .Remove.
The first argument indicates by index number which ListSubItem should be deleted.
The first ListSubItem has index number 1

The method .Clear deletes all ListSubItems in a certain ListItem (‘Record’).

3 Listview elements can contain icons:
— the ColumnHeader
— a ListItem
— a ListSubItem

These elements are being shown by its icon and/or text.
Icon are not part of the ListView itself.
Icons are being stored in separate ‘ImageLists’ in the Userform or the Worksheet.
The ImageList is part of the same library that contains the ListView.

Of course this is not applicable to a virtual (invisible) ListView.

The ListView distinguishes between Icons, SmallIcons and ReportIcons.
You need a separate Imagelist for Icons, SmallIcons and ReportIcons since each list can only contain 1 size of images.

In order to make use of Icons every ListView element — ColumnHeader, ListItem or ListSubItem needs to be linked to an Imagelist.
An Imagelist can be part of a Userform or of a worksheet; it doesn’t matter where.

Columnheaders are only visible in the ListView’s reportview.
The use of icons in ColumnHeaders makes only sense if
— the reportview is active (.View = 3)
— the columnheaders are visible ( .HideColumnHeaders = False )

To link icons to columnheaders, a link to an imagelist must be established by the .ColumHeaderIcons property.
If the ListView name in the Userform is LV_00 and the ImageList name in the Userform IL_00 :

When the Imagelist has been linked you can assign an icon to each separate ColumnHeader.
That is happening in the property .Icon of .ColumnHeader.
Each columnheader can have its own, or no icon.

Use the icon’s name in the linked Imagelist.

a new columnheader

Use the icon’s index number in the linked Imagelist

a new columnheader

ListItems can contain normal or small icons.
To show normal icons set the ListView property .View = 0.
To show small icons: .View = 1.

If you want to use normal and small icons you need 2 separate ImageLists, each containing icons of different sizes.
You will have to link these InmageLists by 2 different ListView properties: .Icons and .SmallIcons
Link ‘normal’ icons to ListItems.
Assume the ListView LV_00 and the ImageList with ‘normal’ icons IL_00 :

The next step is to link each ListItem to an icon.
In the ListItems’ property .Icon you link to a ‘normal’ icon.
In the ListItem’s property .SamllIcon you link to a small icon.
The .property .Icon is independent of the property .SmallIcon.

Every icon in an Imagelist has a unique index number and a unique key.
The text in the .Icon property refers to the key in the linked Imagelist.
The text in the .SmallIcon property refers to the key in the linked Imagelist.

The icon’s key in the Imagelist.

The icon’s index number.

Every icon in an Imagelist has a unique index number and a unique key.
A number in the property .Icon refers to the icon’s index number in the linked Imagelist.
A number in the property .SmallIcon refers to the icon’s index number in the linked Imagelist.

To delete the ‘normal’ icon:

To conditionally assign an icon to a ListItem with the IIf-method:

To conditionally assign a small icon to a ListItem with the IIf-method:

ListSubItems (‘fields’) in a ListItem can contain icons.
Only the reportview (.View=3) of the Listview shows them.
No distinction is made between Icons and SmallIcons.
The ListSubItem uses the Imagelist linked in the Listview’s .SmallIcons property.
In this Imagelist you can determine the size of it’s icons.

Assume Listview (LV_00) and ImageList (IL_01):

The property .Reportitem of the ListSubItam contains the key or index number of an icon in the linked ImageList.

A new ListSubItem: key

Change the reference to the icon in the property .ReportIcon; replace it by the value Empty.

If the icon is conditional and you use the method IIf, you also need the value ‘Empty’.

In the .ReportIcon argument:

The ListView has 4 views.
The ListItems are visible in all views.
Only in report-view all ListSubItems (‘fields’) and columnheaders are visible.

The property .View controls how ListItems are being shown.

This ListView.View property has the value lvwIcon or 0.

The ListItems are being sorted from the left upper cell to the right bottom cell.
The ListItems icons are visible dependent of:

The ListView.View property has value lvwSmallIcon or 1.

The ListItems are being sorted from the left upper cell to the right bottom cell.
The ListItems small icons are visible dependent of:

The ListView.View property has value lvwList or 2.

ListItems are being sorted from top to bottom and from left to right in columns.

Small icons are visible dependent of:

The ListView.View property has value lvwReport or 3.

Information is being shown as a table.

Which elements are visible is dependent of

Columnheader Icon
— the property ListView.ColumnHeaderIcons is linked to an ImageList
— the property columnheader(n).Icon contains an index number or Key referring to the linked Imagelist

ListItem text
— the corresponding ColumnHeader is visible

ListItem icon:
— the corresponding ColumnHeader is visible
— the property ListView.SmallIcons is linked to a valid Imagelist
— the property ListItems(j).SmallIcon contains a valid key or valid index number

ListSubItem Text:
— the corresponding ColumnHeader is visible

ListSubItem icon:
— the corresponding ColumnHeader is visible
— the property ListView.SmallIcons is linked to a valid Imagelist
— the property ListSubItems(j).ReprotIcon contains a valid key or valid index number

The ListView has it’s own sorting method.
A ListView is always sorted by ListItem (‘record’)
The sorting uses the columnheaders indices.
Sorting without columnheaders isn’t possible

Sorting is dependent of

All ‘fields’ in a ListView are string values.
Sorting is based on the property .Text of ListItems and ListSubItems.
So sorting is always alphanumeric.
For sorting of numbers and dates: see 9.1.

ListView sorting by ListItem

.Sorted = 1
.SortKey = 0
.SortOrder = 0
.SortOrder = lvwascending
.SortOrder = 1
.Sortorder = lvwdescending

Источник

Excel VBA ListView Control Examples

by Igor Katenov, the lead developer at 10Tec

The native ListView control from the OS Windows is a control allowing you to display items in various layouts. This versatile control can be used in Microsoft Office VBA. In this article you will find some Excel VBA ListView control examples with our analysis of their drawbacks and serious problems.

Adding the ListView control in VBA

Before you can add ListView control in VBA, you need to have the MS Windows common controls pack (MSCOMCTL.OCX) installed and registered in your system. If MSCOMCTL.OCX is registered properly, you can add the ListView control in Excel VBA using the Additional Controls dialog:

Pay attention to the location of MSCOMCTL.OCX in the Additional Controls dialog. This OCX is a 32-bit executable file, and it must be placed in the SysWoW64 system directory but not in System32 in 64-bit versions of Windows. For more info, read the following StackOverflow post:

As you can also conclude after reading this post, the ListView control may be absent in the latest version of Microsoft Office and Windows. Fortunately for all us, we can still download the Microsoft Visual Basic 6.0 Common Controls redistributable package including ListView from this page on Microsoft’s website.

Many developers experienced problems with instantiating common controls like ListView on Excel worksheets after recent updates in the Windows and Office products even if the Windows common controls OCX was registered correctly. To avoid these issues in production code executing on the computers of your clients, you can try to Create ListView in VBA at Runtime. The essential part of the suggested code solution looks like the following:

One important thing related to this code and any other code manipulating the ListView control in Excel VBA is the following. To use the specific ListView control types and properties in VBA code (like the ListView type itself, the LabelEdit and CheckBoxes properties, the lvwAutomatic named constant and the like), you need to add the reference to the MSComctlLib type library implemented in the same MSCOMCTL.OCX file to your Excel VBA project. If you do not do this, Excel VBA will highlight every member related to ListView with the message «Compile error: User-defined type not defined».

To add a reference to the MSComctlLib type library in your Excel VBA project, use the ToolsReferences dialog in Excel VBA:

If you do not find the «Microsoft Windows Common Controls 6.0 (SP6)» record in the list of available controls (which may be the case if you have never used common controls like ListView in Excel VBA), press the Browse button to select the MSCOMCTL.OCX file on your hard drive. Generally you will find it in the Windows System directory (System32 or SysWoW64 depending on the edition of your Windows).

Opening the References dialog in Excel VBA may fail with the «Error accessing the system registry» message in the latest versions of Windows like Windows 7 or Windows 10. If you see this, you need to relaunch the Microsoft Excel application with administrator rights to grant this application full access to the Windows registry for operations with COM type libraries.

Edit subitems in ListView in Excel VBA

The ListView control provides you with the in-place editing capability to edit item labels. However, if your ListView control works in the report (details) view to imitate a grid control, there is no built-in tool to edit ListView subitems.

You can find a lot of Visual Basic examples of how to implement editing for ListView subtitems in the Internet. All these solutions are based on the same idea: you need to add an additional text box control to your form containing the editable ListView control and place this extra text box over the required subitem when the user is going to edit it.

If try to go this way to implement editable ListView in Excel VBA, you will face two serious troubles related to this development environment. First, the vast majority of published solutions imply that you deal with pixel coordinates everywhere. But control positions and sizes in UserForms are measured in points, so you will need to convert them from points to pixels with helper functions based on the Windows API GetDeviceCaps call (see, for example, this link).

The other problem is that you cannot place the VBA TextBox control from the Microsoft Forms 2.0 package over the ListView control in VBA. Even if you can make this construction work with another text box control, think about reusing of this solution for all ListView controls in which you need subitems editing. You will duplicate the ListView editing infrastructure code and this external editor for all these ListView controls. Your Excel VBA solution will be bloated, and it will be very hard to support it.

Checkboxes in ListView subitems

«Add checkboxes in subitems of listview» is a popular Internet search query related to the ListView control. As a rule, people are searching for a solution to this problem when they use ListView in report mode and want to add checkboxes into several ListView columns.

Unfortunately, the best thing you can do using the native ListView features is to place checkboxes only into one column:

You can easily enable checkboxes for ListView items from VBA code by setting the CheckBoxes property of the ListView control to True, but this adds native checkbox controls only to the item labels in the very first column. If you need checkboxes only in one column displayed not on the first place, you can use a simple trick and move the columns with item labels to the required position. The screenshot with the ListView control on a UserForm above was captured after we had launched the form with the following initialization code, which is an example of how to add ListView subitems in Excel VBA:

However, this approach does not work if you need checkboxes in ListView subitems in several columns. An excellent idea how you can imitate real checkbox controls in ListView subitems was discussed on VBForums in this thread:

The idea is to use a picture of checkbox and display it in the required subitems. Fortunately, ListView allows us to easily add pictures to its subitems in the ListSubItems.Add method with its optional fourth parameter named ReportIcon . The checkbox image can be stored in the ImageList control from the aforementioned Windows common controls pack available for using on UserForms in Excel VBA as well. Below is one more Excel VBA code sample for the ListView control in which we show how to add images to ListView subitems:

This is a neat solution to display Boolean values as checkboxes in ListView columns. But if you need to provide your users with the ability to change the statuses of the ListView checkboxes interactively by clicking them, you will need to write a lot of code to support this infrastructure and duplicate it together with the ImageList control storing the checked and unchecked checkbox images for every required ListView control in your Excel VBA project.

Conclusion

We examined several common usage examples for the ListView control in Excel VBA and saw that we may encounter troubles even in all these ordinary scenarios. We tried to provide solutions or workarounds if they are possible, but an alternative way could be using our iGrid ActiveX grid in Excel VBA for ListView in report view. You will never face any of the problems mentioned above with 10Tec’s iGrid in Excel VBA and will get much more benefits, like built-in grouping/sorting, in-place editing of cells with the text and checkbox editors, fast flicker-free drawing code and dynamic cell formatting. Explore the product pages and articles on this website to find out more about 10Tec’s Excel VBA ListView control alternative. You can start reading from the following article:

Источник

Заполнение ListView

Dмитрий

Дата: Суббота, 24.05.2014, 20:51 |
Сообщение № 1

Группа: Пользователи

Ранг: Участник

Сообщений: 91


Репутация:

9

±

Замечаний:
40% ±


Excel 2010

Всем Доброго времени суток! Мне для работы приходится как-то упорядочивать и выводить массу данных. Использую многостолбцовый ListBox. Данные выводятся по различным условиям (месяц, год и …..). Но в ListBox есть несколько недостатков, которые несколько ухудшают восприятие.
1. Нет возможности увидеть всю строчку в столбце (можно, конечно использовать доп. элементы, но это не вариант)
2. Нет возможности задать разный цвет отдельным строкам (это большой плюс, визуально сразу видно, что, например какие-то данные не в порядке).
Знаю, что в ListBox реализовать это не представляется возможным, в отличие от ListView. Вот и хотелось бы спросить, у знающих людей, кто использовал этот элемент. Как заполнить ListView с несколькими столбцами, установить начальный их размер.
Например, сейчас я заполняю ListBox так:[vba]

Код

ListBox1.Clear
lr = Cells(Rows.Count, 1).End(xlUp).Row
j = 0
For i = 1 To lr Step 1
If Cells(i, 2) Like «*» & TextBox1 & «*» Then
ListBox1.AddItem Cells(i, 1)
ListBox1.List(j, 1) = Cells(i, 2)
j = j + 1
End If
Next i

[/vba]
Искал какую-нибудь литературу — ничего дельного. Может кто-нибудь что-нибудь подскажет и посоветует
Образно набросал небольшой файлик с ListBox

К сообщению приложен файл:

ListBox.xlsb
(15.1 Kb)

Сообщение отредактировал DмитрийСуббота, 24.05.2014, 20:53

 

Ответить

wild_pig

Дата: Суббота, 24.05.2014, 22:30 |
Сообщение № 2

Группа: Проверенные

Ранг: Обитатель

Сообщений: 516


Репутация:

97

±

Замечаний:
0% ±


2003, 2013

ListView, правда на французском )

 

Ответить

nilem

Дата: Суббота, 24.05.2014, 22:52 |
Сообщение № 3

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

вот такой примерчик сохранился (листвью с фильтром) — может, подойдет?


Яндекс.Деньги 4100159601573

 

Ответить

Dмитрий

Дата: Воскресенье, 25.05.2014, 14:18 |
Сообщение № 4

Группа: Пользователи

Ранг: Участник

Сообщений: 91


Репутация:

9

±

Замечаний:
40% ±


Excel 2010

nilem, спасибо. Пытаюсь разобраться. С колонками, размерами — понятно, но как заполнить конкретные столбцы[vba]

Код

With ListView1.ColumnHeaders
         .Clear
         .Add , , «N», 30
         .Add , , «Наименование объекта», 200
         .Add , , «Адрес объекта», 200
     End With
ListView1.ListItems.Add = Cells(i, 1) ‘ так заполняет через строчку
ListView1.ListItems(1).ListSubItems.Add , , Cells(i, 2)’ так распределяет столбец по строкам

[/vba] Пробовал еще кучу вариантов, но везде выдает ошибку.
В примере ListBox, как должно быть

 

Ответить

nilem

Дата: Воскресенье, 25.05.2014, 15:40 |
Сообщение № 5

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

наверное, как-то так:
[vba]

Код

Private Sub CommandButton1_Click()
Dim i&
With Me.ListView1
     For i = 10 To 1 Step -1
         With .ListItems.Add
             .Text = Cells(i, 1)
             .ListSubItems.Add , , Cells(i, 2)
             .ListSubItems.Add , , Cells(i, 3)
         End With
     Next i
End With
End Sub

[/vba]


Яндекс.Деньги 4100159601573

 

Ответить

Alex_ST

Дата: Понедельник, 26.05.2014, 08:43 |
Сообщение № 6

Группа: Друзья

Ранг: Участник клуба

Сообщений: 3176


Репутация:

604

±

Замечаний:
0% ±


2003

Я в 2012 году (сейчас уже ничего почти не помню :( ) разбирался с ListView. Думал применить его на работе, но что-то отвлекло, а потом и надобность отпала…
Помню только, что на старой Планете тему курили и, кажется, была проблема с неуверенной работой на разных машинах из-за разницы версий в библиотеках. (Хотошо, что попробовал перейти по ссылке. Не знаю, почему, но ссылка на Планету получилась битая :( попробую напрямую адрес дать: http://www.planetaexcel.ru/forum….D=39876 )
Однако то, что нарыл/наплодил у себя в копилке сохранил. Сейчас выложил на Гугл.Диск и расшарил.
Поройтесь. Там много всего. Но только я через недельку-другую удалю — у меня на Диске место заканчивается и придётся его скоро чистить.



С уважением,
Алексей
MS Excel 2003 — the best!!!

Сообщение отредактировал Alex_STПонедельник, 26.05.2014, 08:57

 

Ответить

Dмитрий

Дата: Понедельник, 26.05.2014, 10:44 |
Сообщение № 7

Группа: Пользователи

Ранг: Участник

Сообщений: 91


Репутация:

9

±

Замечаний:
40% ±


Excel 2010

Всем спасибо, за помощь! nilem, и Alex_ST, отдельно ОГРОМНОЕ. Вчера до утра мучался, но все-таки добил ListView, внедрил вместо Listbox. Все классно работает. Сегодня утром пришел на работу, запустил и ….. а все так хорошо начиналось. Дома Win7.32, на работе Win7.64 — беда.
Перешел по ссылке Alex_ST, My WebPage, скачал MSCOMCTL.OCX, вставил в папку C:WindowsSysWOW64, зарегистрировал, вроде успешно. Перезагрузил, после этого, я так понимаю ListView должен был появиться в Additional Controls — пусто.
Я понимаю, что тема, может не супер, но так жалко, Control ведь классный и так все хорошо работало на Win7.32, а я уже таких планов настроил…..
[p.s.]Попробую еще зарегистрировать в system32
Возможно библиотека Microsoft Windows Common Controls 6.0 как-то отдельно подключается.

 

Ответить

Alex_ST

Дата: Понедельник, 26.05.2014, 11:52 |
Сообщение № 8

Группа: Друзья

Ранг: Участник клуба

Сообщений: 3176


Репутация:

604

±

Замечаний:
0% ±


2003

Да потому от его использования и пришлось в конце-концов отказаться, что это кОнтрол с непредсказуемым на разных машинах поведением.
У меня на всех компах Win-32 и ListView нормально работает на MSCOMCTL.OCX с версиями:
Версия файла : 6.1.98.39
Версия продукта : 6.01.9839
Я его тоже выложил на Гугл.Диск в ту же расшаренную папку.

Проверьте версию MSCOMCTL.OCX на своих компах этой процедурой:
[vba]

Код

Sub FileVersion()
    Dim sPath$: sPath = «C:WindowsSystem32»
    Dim sFileName$: sFileName = «MSCOMCTL.OCX»
    Dim iNum%, oFolder As Object, oFile As Object
    ‘Set oFolder = CreateObject(«Shell.Application»).Namespace(CVar(sPath))
    Set oFolder = CreateObject(«Shell.Application»).Namespace((sPath))
    Set oFile = oFolder.ParseName(sFileName)
    iNum = 156
Debug.Print oFolder.GetDetailsOf(oFolder.Items, iNum) & » : » & oFolder.GetDetailsOf(oFile, iNum)
    iNum = 271
Debug.Print oFolder.GetDetailsOf(oFolder.Items, iNum) & » : » & oFolder.GetDetailsOf(oFile, iNum)
End Sub

[/vba]



С уважением,
Алексей
MS Excel 2003 — the best!!!

 

Ответить

Dмитрий

Дата: Понедельник, 26.05.2014, 14:31 |
Сообщение № 9

Группа: Пользователи

Ранг: Участник

Сообщений: 91


Репутация:

9

±

Замечаний:
40% ±


Excel 2010

Ну вроде домучал, даже дышать легче стало. Перепробовал массу вариантов, даже сейчас сложно сказать, в чем была причина. Буду дальше разрабатывать, не пришлось бы в итоге после стольких мучений вообще отказаться от данного контролла :(

 

Ответить

Alex_ST

Дата: Понедельник, 26.05.2014, 14:44 |
Сообщение № 10

Группа: Друзья

Ранг: Участник клуба

Сообщений: 3176


Репутация:

604

±

Замечаний:
0% ±


2003

не пришлось бы в итоге после стольких мучений вообще отказаться от данного контролла

Вот именно про этот вариант я и писАл:

потому от его использования и пришлось в конце-концов отказаться, что это кОнтрол с непредсказуемым на разных машинах поведением



С уважением,
Алексей
MS Excel 2003 — the best!!!

Сообщение отредактировал Alex_STПонедельник, 26.05.2014, 23:00

 

Ответить

Dмитрий

Дата: Понедельник, 26.05.2014, 16:14 |
Сообщение № 11

Группа: Пользователи

Ранг: Участник

Сообщений: 91


Репутация:

9

±

Замечаний:
40% ±


Excel 2010

Ну что же, пока сам лоб не разобьешь, за локти кусать не будешь %)

 

Ответить

The ListView, one of the Windows Common Controls introduced with Visual Basic, provides a more polished look to your Userforms than a standard ListBox control. In order to use this control, you must add a reference to “Microsoft Windows Common Controls 6.0 (SP6)” (MSCOMCTL.OCX) to the project. As long as you’re not using the 64-bit version of Excel 2010, these controls will not present a problem. If you are using 64-bit Excel 2010, you will not be able to use the ListView control (and, as far as I know, Microsoft has no replacement in the works).

For those who are not familiar with the ListView control, this post will introduce you to the basics of configuring and populating one for your UserForm-centric Excel application. I’ll discuss some of the basic settings I prefer to give the ListView a polished, professional look. And finally, I briefly list some of the quirks and gotcha’s you need to be aware of.

Fire up Excel and let’s get started.

1. Create a new project.

2. In the Visual Basic Environment, add a reference to the common controls. Tools… References… Microsoft Windows Common Controls 6.0.

3. Add a standard module, name it “modControls” and add the following subroutine:


Public Sub SetCommonListViewProperties(ByRef ListViewToSet As MSComctlLib.ListView)

With ListViewToSet
  .View = lvwReport
  .FullRowSelect = True
  .Gridlines = True
  .MultiSelect = False
  .HideColumnHeaders = True
  .LabelEdit = lvwManual
  .HideSelection = False
  .ColumnHeaders.Clear
End With

End Sub

This will give the ListView grid-like appearance and behavior.

4. Add a new UserForm to the project, name it frmListView.

5. Add a ListView control to the UserForm, name it “lvwTest” and size it to roughly fill the UserForm. Note: If you don’t see the ListView in the control Toolbox, then right-click the Toolbox, select “Additional Controls…”, and search for “Microsoft ListView Control, version 6.0”, and select it by checking the checkbox.

6. Add the following code to the UserForm_Initialize event:


Private Sub UserForm_Initialize()
Dim ch As ColumnHeader
Dim lngRow As Long
Dim ListItem As MSComctlLib.ListItem

SetCommonListViewProperties lvwTest

'Define the columns, even though the actual headers won't be visible.
With lvwTest.ColumnHeaders
Set ch = .Add(, , "First Name", 50, lvwColumnLeft)
Set ch = .Add(, , "Last Name", 100, lvwColumnLeft)
Set ch = .Add(, , "Company", 100, lvwColumnLeft)
Set ch = .Add(, , "Title", 50, lvwColumnCenter)
End With

'Now load some data into the ListView
With lvwTest
.ListItems.Clear
For lngRow = 0 to 4
Set ListItem = .ListItems.Add(, , "FirstName" & CStr(lngRow))
ListItem.SubItems(1) = "LastName" & CStr(lngRow)
ListItem.SubItems(2) = "Test Company"
ListItem.SubItems(3) = IIf(lngRow = 0, "President", "Drone")
Next lngRow
End With

End Sub

7. Test the ListView. To keep things simple, just open the Immediate Window in the VBE and type “frmListView.Show“. You should see your form and ListView with test data.

In addition to presenting the data nicely, the ListView also can be easily coded to sort based on the column header clicked. It’s a well behaved drag & drop source/target and exposes a full set of Enter, Exit, ItemClick, ItemCheck, BeforeUpdate and AfterUpdate events. If only it could be edited in place, it would rival a full featured grid control…

Preferences
In the “SetCommonListViewProperties” listing above, I set the .HideColumnHeaders property to True because I find the built-in column headers to be dull and inflexible. They’re button-gray and cannot be formatted.

ListView with built-in column headers

ListView with built-in column headers

I prefer to create my own column headers using Label controls. They can be formatted with contrasting colors and a wide choice of fonts to give the ListView a bit more pizazz.

ListView with custom column headers

ListView with custom column headers

Quirks

* The ListView does not behave well if placed on a container, such as a panel or frame control, that is subsequently toggled between being hidden and shown. It tends to re-position itself in the top left corner of the container. Same goes for a Tab or Multipage control. I once attempted to place ListViews on several pages of a Multipage control. The first time you view the page, the ListView is plastered in the upper left corner of the container. If you click on a different page and then back to the offending page, the ListView control is back in its proper position. I tried several things to fix it (i.e. explicitly setting the Top, Left properties in the Initialize and Activate events of the UserForm; explicitly refreshing the UserForm; re-positioning the ListView within the Click event of the Multipage control), all to no avail. I finally discovered a kluge: In the Click event of the Multipage control, if I make all the ListViews invisible and then visible again, the problem goes away.

* The x and y arguments for the MouseDown or OLEDragOver events must be manipulated before they can be passed accurately to the HitTest method of the ListView. This is a known issue and is addressed on many, many Q&A forums, so I’m not going to go into any detail here. Just do a search for “HitTest Excel UserForm” and you’ll see what I mean. This also pertains to the TreeView control.

* Clicking the “(Custom)” property of the ListView in order to use the graphical interface for defining columns, you may see a “Class Not Registered” error. This is something you’ll more commonly see with Windows Vista and Windows 7 and is caused by a missing or un-registered DLL called Msstkprp.dll. Do a search for this to get the details of how to download and register it.

Summary
The post is mainly for those of you who are not familiar with the Windows Common Controls. The ListView control and the TreeView control can really add polish and a professional appearance to your UserForm-centric Excel applications. You should familiarize yourself with both controls, and delve a bit more into the functionality that you can tap into for your next project.

+MD

Compatibility Issues working with Application in Older Version Of Office

After the recent upgrades in Microsoft products, we can notice few compatibility issues in components like ListView, TreeView, ImageList etc., when upgrading VBA applications from Office 2003 to New versions. In such scenarios, if you have the corresponding OCX file registered in your machine, It is better to create these controls during run-time.

Sometimes, if we manually add these controls, save it and then open it in another machine, these controls will not appear or work properly (especially ListView). Not sure, whether Microsoft will provide ay fix for this. Sometimes, these controls created in latest version office will not work in older version.

Create Controls At Execution

Creating commands at run-time would solve in some cases. Lets see how to create a ListView when the VBA code is getting executed. Create a New Excel workbook, Pess Alt + F11 to view VB Editor. Copy paste the below code.

Private Sub Create_ListView_Dynamic()
    'Declare Variable Names
    Dim oLv As ListView
    Dim Wsheet As Worksheet
    
    'Create ListView in WorkSheet
    Set Wsheet = ThisWorkbook.Sheets(1)
    Set oLv = Wsheet.OLEObjects.Add(ClassType:="MSComctlLib.ListViewCtrl.2", _
        Link:=False, DisplayAsIcon:=False, Left:=100, Top:=100, Width:=300, Height:=100).Object
    
    'Give ListView Control a Name
    oLv.Name = "ListCust"
    
    'Assign Value to Other Properties
    With oLv
        .Left = 20
        .Top = 20
        .Height = 100
        .Width = 492
        .Visible = True
        .View = lvwReport
    End With
    
End Sub

Run the above code by Pressing F5 Command button. A Listview control will added to the First worksheet in your active Workbook.

Now that we have created the ListView, how do we add the ColumnHeaders and Insert Data

Private Sub Access_ListView_Add_Data()
    'Declare Variable Names
    Dim i As Integer
    Dim oLv As ListView
    Dim oLi As ListItem
    Dim Wsheet As Worksheet
    
    'Get ListView in WorkSheet to an Object
    Set Wsheet = ThisWorkbook.Sheets(1)
    Set oLv = Wsheet.OLEObjects("ListCust").Object
     
    'Clear Header & Add Column Headers
    oLv.ColumnHeaders.Clear
    With oLv
        .ColumnHeaders.Add 1, "Key1", "Key1"
        .ColumnHeaders.Add 2, , "Header2"
        .ColumnHeaders.Add 3, , "Header3"
        .ColumnHeaders.Add 4, , "Header4"
        .ColumnHeaders.Add 5, , "Header5"
        .ColumnHeaders.Add 6, , "Header6"
        .View = lvwReport
    End With
    
    'Add Data to ListView
    oLv.ListItems.Clear
    For i = 1 To 5
        Set oLi = oLv.ListItems.Add(i, , "KeyVal" & i)
        oLi.SubItems(1) = "H2Val" & i
        oLi.SubItems(2) = "H2Val" & i
        oLi.SubItems(3) = "H2Val" & i
        oLi.SubItems(4) = "H2Val" & i
        oLi.SubItems(5) = "H2Val" & i
    Next i
    
    'In Some Systems, ListView Value will not be Visible when you just run above code.
    'Execute below code to get the values visible & align properly
    oLv.Visible = False
    oLv.Visible = True
    ActiveSheet.Shapes("ListCust").Select
    With Selection
        .Placement = xlFreeFloating
        .PrintObject = True
    End With
    ActiveWindow.SmallScroll Down:=-24
    ActiveWindow.SmallScroll Up:=24
    
End Sub

Hope this is helpful when you want to create OLEobjects at runtime. Leave your comments if you like the solution.

This is the continuing saga of putting records on a userform. I followed up on Rob’s suggestion of the ListView control and I like it. I wouldn’t call it its use intuitive, but once you get the hang of it, it’s O.K.

I don’t have this whole thing figured out yet, but I’ll show you what I do have. Suggestions and corrections are always welcome. It all starts with the showform3 procedure:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

Sub showform3()

    Dim colRecords As Collection

    Dim ufScroll As UScroll2

    Dim i As Long

    ‘Fill a collection with CRecord objects – pretty much the same code

    ‘as the previous posts, just put into a function.

    Set colRecords = New Collection

    Set colRecords = FillRecords

    ‘Create a new instance of the userform rather than relying on the

    ‘default instance

    Set ufScroll = New UScroll2

    ‘Load the records into a custom property of the userform

    Set ufScroll.Records = colRecords

    ufScroll.Show  ‘Show the form. Code is suspended at this point

    ‘Get the new records, if any, from the userform’s property

    Set colRecords = ufScroll.Records

    ‘Print out the records to make sure I didn’t miss something

    For i = 1 To colRecords.Count

        Debug.Print colRecords(i).Name, colRecords(i).Department, colRecords(i).Current

    Next i

End Sub

When the Show method is called, the Activate event fires. In addition to filling the Department combobox, the Activate event adds three columns to the ListView via the ColumnHeaders.Add method. I set the first two column’s width equal to the controls above and just threw in a number for the Current column.

Next, I set a few properties for the ListView. The HideColumnHeaders property is False by default, but I set it in code explicitly. The View property is important if you want columns. Setting View equal to lvwReport is similar (exactly?) like choosing Details when you’re viewing a Windows Explorer window. The default view is like the List view in Windows, where subitems are not shown. Finally I show gridlines because I like the way it looks.

In the next section, I loop through all the CRecord objects in the collection and add them to the ListView. I add ListItems using the Name property and add SubItems 1 and 2 to hold the Department and Current properties. Finally, I run the ItemClick event to populate my edit controls.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

Private Sub UserForm_Activate()

    Dim i As Long

    Dim li As ListItem

    Dim vaDepts As Variant

    vaDepts = Array(«Accounting», «Marketing», «Production», «Information Technology», «Shipping»)

    For i = LBound(vaDepts) To UBound(vaDepts)

        Me.cbxDept.AddItem vaDepts(i)

    Next i

    With Me.ListView1

        .ColumnHeaders.Add , , «Name», Me.tbxName.Width         ‘Add columns

        .ColumnHeaders.Add , , «Department», Me.cbxDept.Width

        .ColumnHeaders.Add , , «Current», 50

        .HideColumnHeaders = False  ‘set some properties

        .View = lvwReport

        .Gridlines = True

        For i = 1 To mcolRecords.Count                       ‘populate listview

            Set li = .ListItems.Add(, , mcolRecords(i).Name)

            li.SubItems(1) = mcolRecords(i).Department

            li.SubItems(2) = mcolRecords(i).Current

        Next i

        ListView1_ItemClick .ListItems(.SelectedItem.Index) ‘fill edit controls

    End With

End Sub

The ItemClick event fills the textbox, combobox, and checkbox so the user can edit the selected item. The other ListView event I use is the ColumnClick event. I haven’t quite got the sorting thing figured out yet, but I can toggle ascending and descending on the Name column.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

Private Sub ListView1_ColumnClick(ByVal ColumnHeader As MSComctlLib.ColumnHeader)

    If ColumnHeader.Text = «Name» Then

        Me.ListView1.Sorted = True

        Me.ListView1.SortKey = 0

        If Me.ListView1.SortOrder = lvwDescending Then

            Me.ListView1.SortOrder = lvwAscending

        Else

            Me.ListView1.SortOrder = lvwDescending

        End If

    Else

        Me.ListView1.Sorted = False

    End If

End Sub

Private Sub ListView1_ItemClick(ByVal Item As MSComctlLib.ListItem)

    With Item

        Me.tbxName.Text = .Text

        Me.cbxDept.Value = .SubItems(1)

        Me.chkCurrent.Value = .SubItems(2)

    End With

End Sub

The Delete and New buttons’ code is shown below. The Delete code is pretty straight forward. The mbIsDirty variable stores whether changes have been made. This will come into play in the Close button code. The New button code clears the edit boxes and set the focus ready to create a new list item. It also changes the caption of the button next to the edit controls from Save to Add in an attempt to make it intuitive for the user.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Private Sub cmdDel_Click()

    With Me.ListView1

        .ListItems.Remove .SelectedItem.Index

    End With

    mbIsDirty = True

End Sub

Private Sub cmdNew_Click()

    Me.tbxName.Text = «»            ‘Clear the edit controls

    Me.cbxDept.Value = «»

    Me.chkCurrent.Value = False

    Me.tbxName.SetFocus

    Me.cmdCommit.Caption = «Add»    ‘change the commit button caption

    Me.cmdCommit.Accelerator = «A»

End Sub

The Commit button, which either says Save or Add depending on whether the user is editing an existing record or adding a new one, uses the code shown below. Depending on the caption of the button, it adds a new ListItem (and related SubItems) or changes the currently selected ListItem. It then changes the button’s caption and updates mbIsDirty to reflect that the data has changed.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

Private Sub cmdCommit_Click()

    If Me.cmdCommit.Caption = «Add» Then

        With Me.ListView1.ListItems.Add(, , Me.tbxName.Text)

            .SubItems(1) = Me.cbxDept.Value

            .SubItems(2) = Me.chkCurrent.Value

            .Selected = True

            .Top = Me.ListView1.Top

        End With

    Else

        With Me.ListView1.ListItems(Me.ListView1.SelectedItem.Index)

            .Text = Me.tbxName.Text

            .SubItems(1) = Me.cbxDept.Value

            .SubItems(2) = Me.chkCurrent.Value

        End With

    End If

    Me.cmdCommit.Caption = «Save»

    Me.cmdCommit.Accelerator = «S»

    mbIsDirty = True

End Sub

The Apply button creates a new collection if anything has been changed. The variable mcolRecords contains the collection that was originally passed into the form until this procedure is called, at which time it is overwritten with whatever is in the ListView. Rewriting the collection is fine for this twenty-six member collection, but I’d have to come up with something better if there were a lot of records. I should probably disable this button until mbIsDirty is True also.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

Private Sub cmdApply_Click()

    Dim clsRecord As CRecord

    Dim i As Long

    If mbIsDirty Then

        Set mcolRecords = New Collection

        With Me.ListView1.ListItems

            For i = 1 To .Count

                Set clsRecord = New CRecord

                clsRecord.Name = .Item(i).Text

                clsRecord.Department = .Item(i).SubItems(1)

                clsRecord.Current = .Item(i).SubItems(2)

                mcolRecords.Add clsRecord, CStr(i)

            Next i

        End With

        mbIsDirty = False

    End If

End Sub

Finally, the Close button hides the form, returning control back to showform3. If any of the data has changed and not been ‘applied’, this sub will ask the user what to do.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Private Sub cmdClose_Click()

    Dim lResp As Long

    Dim sMsg As String

    sMsg = «Save Changes?»

    If mbIsDirty Then

        lResp = MsgBox(sMsg, vbYesNoCancel, Me.Caption)

        If lResp = vbYes Then

            cmdApply_Click

            Me.Hide

        ElseIf lResp = vbNo Then

            Me.Hide

        End If

    Else

        Me.Hide

    End If

End Sub

You can download UFScroll.zip.

hi,

we must add the first value of the row (column 1),  to create index, then add the others values of this row (columns 2 to 6)

Private Sub UserForm_initialize()
Dim sh As Worksheet, rng As Range, LastRow As Long, LastColumn As Long, y As Long

Set sh = Sheets(«Feuil1») ‘adapt sheet name
LastRow = sh.Cells(sh.Range(«A1»).SpecialCells(xlCellTypeLastCell).Row + 1, 1).End(xlUp).Row
LastColumn = sh.Cells(1, sh.Range(«A1»).SpecialCells(xlCellTypeLastCell).Column + 1).End(xlToLeft).Column

With Me.ListView1
    With .ColumnHeaders
        .Clear
        For i = 1 To LastColumn
        .Add , , sh.Cells(1, i)
        Next
    End With
     .View = 3                   ‘ report type
    .Gridlines = True           ‘ show Rows
    .FullRowSelect = True       ‘ complete selection of line
    .HideColumnHeaders = False  ‘ show «columns headers»
    .LabelEdit = 1              ‘ doesn’t authorize writing
End With

ListView1.ListItems.Clear
With Sheets(«Feuil1»)
    Set rng = sh.Range(sh.Cells(2, 1), sh.Cells(LastRow, 1))
    For Each Cel In rng
        With ListView1
            .ListItems.Add , , Cel         ‘add the first value of the row (column 1),  to create index
            For y = 2 To LastColumn   ‘add the others values of this row (columns 2 to 6)
            .ListItems(.ListItems.Count).ListSubItems.Add , , sh.Cells(Cel.Row, y)
            Next
        End With
    Next
End With

End Sub


isabelle

Le 2011-04-14 21:24, klnp a écrit :

Hi,

How to add column header and sub items to listview in excel vba. My first row contains column headers. I want to display the first 6 columns («A1:F1») and display all it subitems

Regards

The following code fills a ListView on a UserForm with data from an Excel worksheet. It is assumed that you’ve already created a UserForm that contains a ListView. It is also assumed that Sheet1 contains the data, starting at A1, and that the first row contains the column headers.

Private Sub UserForm_Activate()

    ‘Set a reference to Microsoft Windows Common Controls by
    ‘using Tools > References in the Visual Basic Editor (Alt+F11)

    ‘Set some of the properties for the ListView
    With Me.ListView1
        .Gridlines = True
        .HideColumnHeaders = False
        .View = lvwReport
    End With

        ‘Call the sub to fill the ListView
    Call LoadListView

    End Sub

Private Sub LoadListView()

    ‘Declare the variables
    Dim wksSource As Worksheet
    Dim rngData As Range
    Dim rngCell As Range
    Dim LstItem As ListItem
    Dim RowCount As Long
    Dim ColCount As Long
    Dim i As Long
    Dim j As Long

        ‘Set the source worksheet
    Set wksSource = Worksheets(«Sheet1»)

        ‘Set the source range
    Set rngData = wksSource.Range(«A1»).CurrentRegion

        ‘Add the column headers
    For Each rngCell In rngData.Rows(1).Cells
        Me.ListView1.ColumnHeaders.Add Text:=rngCell.Value, Width:=90
    Next rngCell

        ‘Count the number of rows in the source range
    RowCount = rngData.Rows.Count

        ‘Count the number of columns in the source range
    ColCount = rngData.Columns.Count

        ‘Fill the ListView
    For i = 2 To RowCount
        Set LstItem = Me.ListView1.ListItems.Add(Text:=rngData(i, 1).Value)
        For j = 2 To ColCount
            LstItem.ListSubItems.Add Text:=rngData(i, j).Value
        Next j
    Next i

    End Sub

Where to Put the Code

  1. Open the workbook in which to store the code.
  2. Open the Visual Basic Editor (Alt+F11).
  3. In the Project Explorer window (Ctrl+R), right-click the UserForm, and select View Code.
  4. Copy and paste the above code into the code module for the UserForm.
  5. Return to Microsoft Excel (Alt+Q).
  6. Save the workbook.

Sample Workbook: Download

Like this post? Please share to your friends:
  • Lists of words in excel
  • Logistics the meaning of the word
  • Lists of word family words
  • Login and password in one word
  • Log file in excel