For Loop not passing caption from a listbox to an array

boweryreserve

New Member
Joined
Feb 10, 2014
Messages
19
Greetings,

I’m having an issue wherein a for loop isn’t passing the caption from a listbox to an array. When I add the variable SheetsFound to the Watch window, the value is always empty yet when the loop evaluates whether listbox value is check or unchecked, it verifies which listbox value is checked. I feel the issue resides in Private Sub CommandButton2_Click().

Does anyone know what’s happening here? Many thanks.

Code:
Private Sub UserForm_Initialize()
Dim sSheet As Variant
Dim ListItem As Variant
Dim WorksheetCount As Long
Dim iCounter As Integer
    
'For every worksheet in this workbook add the worksheet name as an item in ListBox1.
    For Each sSheet In Sheets
            ListBox1.AddItem sSheet.Name
    Next sSheet
'Count of items in ListBox1 (puts output in Immediate Window)
    Debug.Print ListBox1.ListCount
'##################
'Counts the number of worksheets
    WorksheetCount = ActiveWorkbook.Worksheets.count
    Debug.Print WorksheetCount
'Message box with name of each item in ListBox1 (i.e. the name of each worksheet in workbook)
'    For i = 0 To (ListBox1.ListCount - 1)
'        MsgBox ListBox1.List(i)
'    Next
                                
End Sub
Private Sub CheckBox1_Click()
'CheckBox1 refers to the "Select/Deselect All" check box.
Dim iloop As Integer
    For iloop = 1 To ListBox1.ListCount
        ListBox1.Selected(iloop - 1) = CheckBox1.Value
    Next
End Sub
Private Sub CommandButton1_Click()
    
    Unload Me
End Sub
Private Sub CommandButton2_Click()
  Dim fName As String
  Dim myPath As String
  Dim myOutput As String
  Dim FileNameWithoutExtension As String
  Dim ThisWorkbookPath As String
  Dim FullFileName As String
  Dim SheetsFound() 'This is an array
 
 'Message box with name of each item in ListBox1 (i.e. the name of each worksheet in workbook)
    For i = 0 To (ListBox1.ListCount - 1)
'Asks if the listbox if checked: it it returns false then unchecked; if it returns true, it is checked.
        Debug.Print ListBox1.Selected(i) = True
        Debug.Print Me.Controls(ListBox1.Selected(i)).Caption
    
    Next
  
'Resizes the array to 0 which corresponds to 1. Redim/resize the array to 0, so it will be able to hold 1 item in it.
  ReDim SheetsFound(0)
'For each item in list (starting at 1 [i=0] and ending at the number based on the list count).
  For i = 0 To ListBox1.ListCount
'If the ListBoxItemNumber is checked, then...
    If Me.Controls(ListBox1.Selected(i)).Value = True Then
'What is the Caption of the ListBoxItem?
                Debug.Print Me.Controls(ListBox1.Selected(0)).Caption
                
        SheetsFound(UBound(SheetsFound)) = Me.Controls(ListBox1.Selected(i)).Caption
        ReDim Preserve SheetsFound(UBound(SheetsFound) + 1)
    Else: On Error Resume Next
    End If
  Next i
  ReDim Preserve SheetsFound(UBound(SheetsFound) - 1)
  Sheets(SheetsFound).Select
'########################
'Retrieve ActiveWorkbook's File Path (Displayed in Immediate Window [ctrl + g])
  myPath = ActiveWorkbook.FullName
  Debug.Print "File Path: " & myPath
   
'######### Change Path to Actual Path ############
'    ThisWorkbookPath = ThisWorkbook.Path & "\"                    'Notice the trailing \
    FullFileName = Left(myPath, InStrRev(myPath, ".") - 1) & ".pdf"
    Debug.Print FullFileName
If Not FileFolderExists(FullFileName) Then  'See if the Filename already Exists
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                                    FileName:=FullFileName, _
                                    quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
                                    OpenAfterPublish:=True
  Else
    MsgBox FullFileName & " already exists"
  End If
End Sub
 

Excel Facts

Select a hidden cell
Somehide hide payroll data in column G? Press F5. Type G1. Enter. Look in formula bar while you arrow down through G.
Instead of:
Code:
    For i = 0 To (ListBox1.ListCount - 1)
        'Asks if the listbox if checked: it it returns false then unchecked; if it returns true, it is checked.
        Debug.Print ListBox1.Selected(i) = True
        Debug.Print Me.Controls(ListBox1.Selected(i)).Caption    
    Next
try this:
Code:
    For i = 0 To (ListBox1.ListCount - 1)
        'Asks if the listbox if checked: it it returns false then unchecked; if it returns true, it is checked.
[COLOR=#0000ff]        If ListBox1.Selected(i) Then [/COLOR]Debug.Print [COLOR=#0000FF]ListBox1.List(i, 0)[/COLOR]
    Next
 
Upvote 0
Hi,

This is helpful as it evaluates whether Listbox1.List(i,0) is checked and what the name of the Listbox1.List(i,0) is.

I got loop to pass the Listbox1.List(I,0) to the array but now I end up with the following issues.

1. When I reach the point where it should save as PDF, it only saves the first worksheet, irrespective of which list name I choose.

The intent of this code is to create a userform that automatically pulls in each worksheet name and allows the user to choose which worksheets to save as PDF.
 
Upvote 0
What do you mean by the 'caption' of the listbox?

Listboxes don't have captions.

If you want to create an array containing all the selected items in the listbox try something like this.
Code:
Dim SheetsFound()
Dim cnt As Long
Dim I As Long

    With ListBox1
        For I = 0 To .ListCount-1
            If .Selected(I) Then
                Redim Preserve SheetsFound(cnt)
                SheetsFound(cnt) = .List(I)
                cnt = cnt +1 
            End If
        Next I
    End With

    If I>0 Then 
        ' code to print selected sheets to PDF file
    End If
[/code]
 
Upvote 0
In CommandButton2_Click, replace:
Code:
Sheets(SheetsFound).Select

with:
Code:
selectSheets (SheetsFound)

Code of the subroutine:
Code:
Sub selectSheets(sheetNames As Variant)
    Dim x As Variant
    
    ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count).Select
    For Each x In sheetNames
        Worksheets(x).Select (False)
    Next x
End Sub
 
Upvote 0
Thanks to both of you. This has been very helpful. I'm almost there.

The last issue I see when I test is that I get the following error message: Run-time error '-2147024809 (80070057)': Invalid Argument.

anytime I choose the first worksheet in the Userform.

The code stops and highlights the following line in yellow: If Me.Controls(ListBox1.Selected(I)).Value = True Then

Does anyone know what's happening here?


Code:
  ReDim SheetsFound(0)
'For each item in list (starting at 1 [i=0] and ending at the number based on the list count).
  For I = 0 To ListBox1.ListCount
'If the ListBoxItemNumber is checked, then...
    If Me.Controls(ListBox1.Selected(I)).Value = True Then
        SheetsFound(UBound(SheetsFound)) = ListBox1.List(I)
        ReDim Preserve SheetsFound(UBound(SheetsFound) + 1)
    Else: On Error Resume Next
    End If
  Next I
  ReDim Preserve SheetsFound(UBound(SheetsFound) - 1)
 
Upvote 0
What are you trying to refer to with ListBox1.Selected(I) here?
Code:
Me.Controls(ListBox1.Selected(I)).Value

ListBox1.Selected(I) will return True/False, are you trying to refer to a control on the userform with the name 'True' or 'False'? That's what VBA thinks you are trying to do.:)

PS Did you try the code I posted to create the array from the selections in the listbox?
 
Upvote 0
Hi,

I am trying to refer to whether ListBox1.Select(I) is checked or not check (i.e. true or false). And it works for any ListBox1.Select(I) that is not = 1. For whatever reason, when the first item in the listbox is selected, I get the run-time error '2417...

Yes, I did try the code you posted but I couldn't get it to work. I was only able to save the first worksheet, regardless of which list item name I choose. I must not have been using your code correctly.

Below is a subset of my revised code which works for any list item that is selected except the first item.

Thanks for your help with all of this.

Code:
Private Sub CommandButton2_Click()
  Dim fName As String
  Dim myPath As String
  Dim myOutput As String
  Dim FileNameWithoutExtension As String
  Dim ThisWorkbookPath As String
  Dim FullFileName As String
  Dim SheetsFound()  'This is an array
  Dim cnt As Long
  Dim I As Long

'###########################
 'Message box with name of each item in ListBox1 (i.e. the name of each worksheet in workbook)
    For I = 0 To (ListBox1.ListCount - 1)
'Asks if the listbox if checked: if it returns false then unchecked; if it returns true, it is checked.
        Debug.Print ListBox1.Selected(I) = True
        Debug.Print Me.Controls(ListBox1.Selected(I)).Caption
            If ListBox1.Selected(I) = True Then
            Debug.Print ListBox1.List(I, 0)
            End If
    Next
  
'Resizes the array to 0 which corresponds to 1. Redim/resize the array to 0, so it will be able to hold 1 item in it.
  ReDim SheetsFound(0)
'For each item in list (starting at 1 [i=0] and ending at the number based on the list count).
  For I = 0 To ListBox1.ListCount
'If the ListBoxItemNumber is checked, then...
    If Me.Controls(ListBox1.Selected(I)).Value = True Then
        SheetsFound(UBound(SheetsFound)) = ListBox1.List(I)
        ReDim Preserve SheetsFound(UBound(SheetsFound) + 1)
    Else: On Error Resume Next
    End If
  Next I
  ReDim Preserve SheetsFound(UBound(SheetsFound) - 1)
Call selectSheets(SheetsFound)

'########################
'Retrieve ActiveWorkbook's File Path (Displayed in Immediate Window [ctrl + g])
  myPath = ActiveWorkbook.FullName
  Debug.Print "File Path: " & myPath
   
'######### Change Path to Actual Path ############
    FullFileName = Left(myPath, InStrRev(myPath, ".") - 1) & ".pdf"
    Debug.Print FullFileName
If Not FileFolderExists(FullFileName) Then  'See if the Filename already Exists
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                                    FileName:=FullFileName, _
                                    quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
                                    OpenAfterPublish:=True
  Else
    MsgBox FullFileName & " already exists"
  End If
End Sub

Sub selectSheets(sheetNames As Variant)
    Dim x As Variant
    ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.count).Select
    For Each x In sheetNames
        Worksheets(x).Select (False)
    Next x
End Sub
 
Upvote 0
Replace
Code:
If Me.Controls(ListBox1.Selected(i)).Value = True Then
with
Code:
If ListBox1.Selected(i) Then

Same for other such occurrences, if any.

Explanation:
You are probably getting an error because Me.Controls(ListBox1.Selected(i)).Value is not the right way to get the selected item - its just ListBox1.Selected(i).

With Me.Controls(x), you look for a control on the entire form (Me is implicit variable for current module, which is the userform in this case). So when the For loop iteration reaches a selected item, this happens:
1. Start evaluating = Me.Controls(ListBox1.Selected(i)).Value
2. i-th item is selected = Me.Controls(True).Value
3. Convert True to int = Me.Controls(-1).Value
4. No item at position -1 in collection = Error
 
Upvote 0
The code I posted was only meant to create the array of the selected items in the listbox, it had nothing to do with printing to PDF.
 
Upvote 0

Forum statistics

Threads
1,221,310
Messages
6,159,173
Members
451,543
Latest member
cesymcox

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top