Reputation: 35
I am trying to make dependent combobox in excel VBA, But I am getting the below error: I am not able to understand why I am getting. Help would be great.
Run-time error '1004': The selection is not valid, There are several possible reasons:
' @@subroutine to add values into comboBox drop down for type of Study
Private Sub UserForm_Initialize()
Dim lastRow As Long
Dim lastColumn As Long
'MsgBox "Value : " & Range("B4").End(xlUp).Select
'MsgBox "Sheet2" & Sheet2.Cells(1, Columns.Count).End(xlToLeft).Column
'MsgBox "Test : " & Sheet5.Cells(1, Columns.Count).End(xlToLeft).Column
lastColumn = 18
'Sheet5.Cells(1, Columns.Count).End(xlToLeft).Column
With Worksheets("Sheet5")
For colsCounter = 1 To lastColumn
With .Columns(colsCounter)
lastRow = Sheet5.Cells(Rows.Count, colsCounter).End(xlUp).Row
With Range(Cells(1, colsCounter), Cells(lastRow, colsCounter))
Range(Cells(1, colsCounter), Cells(lastRow, colsCounter)).Select
Selection.CreateNames Top:=True
'Selection.CreateNames Top:=True, Left:=False, Bottom:=False, Right:=False
End With
End With
Next colsCounter
End With
latLandingForm.cmbLSPList.RowSource = "LspList"
Upvotes: 2
Views: 984
Reputation: 17637
Your final With
isn't correct. Try:
With Worksheets("Sheet5")
For colsCounter = 1 To lastColumn
With .Columns(colsCounter)
lastRow = Sheet5.Cells(Sheet5.Rows.Count, colsCounter).End(xlUp).Row
With .Range(.Cells(1, colsCounter), .Cells(lastRow, colsCounter))
.CreateNames Top:=True
End With
End With
Next
End With
You can only nest a With
block if it is a child item of the previous block:
'// This will work fine
With Sheets("Sheet1")
With .Range("A1") '// Notice the '.' before Range()
.Value = "test"
End With
End With
'// This will not
With Sheets("Sheet1")
.Range("A1").Value = "test"
With Sheets("Sheet2")
.Range("A1").Value = "test"
End With
End With
In the second example, you would have to close the previous With
block before starting with the next one.
Upvotes: 1