In the procedure below my combobox populate with the values of a6 through a12. However, I just realized that the range will be dynamic. There may be 3 cells or 1000 depending on the data. How can I adjust the code below to reflect a dynamic range?
Option Strict On
Option Explicit On
Imports Microsoft.Office.Interop.Excel
Public Class dsbPositionBoard
Private Sub dsbPositionBoard_Startup() Handles Me.Startup
'This event runs when the dsbPositionBoard starts up. The procedure
'checks for the values in column A of the allPositionsAnualized sheet
'and populates the combobox with those values.
'Variables for procedure
Dim WB As Excel._Workbook
Dim WS As Excel.Worksheet
Dim rng As Excel.Range
Dim rngArr As String
WB = CType(Globals.ThisWorkbook.Application.ActiveWorkbook, Excel.Workbook)
WS = DirectCast(WB.Sheets("allPositionsAnnualized"), Excel.Worksheet)
rng = DirectCast(WS.Range("A6", "A12"), Excel.Range)
rngArr = String.Empty
'Build a string array delimited by commas
For i As Integer = 1 To rng.Rows.Count
Dim oCell As Excel.Range = DirectCast(rng.Rows(i), Excel.Range)
rngArr &= DirectCast(oCell.Value.ToString, String) & ","
Next
rngArr = rngArr.Remove(rngArr.Length - 1, 1)
cmbSelectPosition.Items.AddRange(rngArr.Split(","c))
rng = Nothing
WS = Nothing
End Sub
If there are no blank cells from A6 downwards then:
rng = DirectCast(WS.Range("A6", WS.Range("A6").End(xlDown)), Excel.Range)
You'll probably need to qualify the xlDown
when running this from VB.NET, using Excel.xlDirection.xlDown
.
But you should also study the link that mehow provided.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.