在下面的过程中,我的组合框填充了a6到a12的值。但是,我才意识到范围将是动态的。根据数据,可能有3个单元或1000个单元。如何调整下面的代码以反映动态范围?
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
答案 0 :(得分:0)
如果A6中没有空白单元格,则:
rng = DirectCast(WS.Range("A6", WS.Range("A6").End(xlDown)), Excel.Range)
使用xlDown
从VB.NET运行时,您可能需要对Excel.xlDirection.xlDown
进行限定。
但你也应该研究mehow提供的链接。