0

在下面的过程中,我的组合框填充了 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
4

1 回答 1

0

如果从 A6 向下没有空白单元格,则:

rng = DirectCast(WS.Range("A6", WS.Range("A6").End(xlDown)), Excel.Range)

xlDown从 VB.NET 运行此程序时,您可能需要使用Excel.xlDirection.xlDown.

但是您还应该研究 mehow 提供的链接。

于 2013-06-27T20:27:21.330 回答