3

我正在尝试拆分字符串并获取拆分部分并将它们分配给变量。这适用于第一个变量,但我无法让第二个变量工作。

For Each columnQuarter As DataColumn In dt.Columns
            Dim s As String = columnQuarter.ColumnName
            Dim words As String() = s.Split("-")
            Dim Year As String = words(0)
            Dim Quarter As String = words(1)
            Debug.WriteLine(Year)
            Debug.WriteLine(Quarter)

在“Dim Quarter As String = words(1)”行,我收到错误代码“IndexOutofRangeException 未处理。索引超出了数组的范围。”

ColumnName 的一个示例是 2012-Q1。

附加信息:

这是我用来将列添加到数据表的代码。如您所见,我的前两列不包含“-”。

tickerColumn = New DataColumn("Ticker", Type.GetType("System.String"))
consistencyColumn = New DataColumn("Consistency", Type.GetType("System.Int32"))
dt.Columns.Add(tickerColumn)
dt.Columns.Add(consistencyColumn)

    With Me
        lr = Now.Year - 1901
        For i = 1 To lr
            column = New DataColumn
            column.DataType = System.Type.GetType("System.Int32")
            column.ColumnName = Now.Year - i & "-Q4"
            dt.Columns.Add(column)

            column = New DataColumn
            column.DataType = System.Type.GetType("System.Int32")
            column.ColumnName = Now.Year - i & "-Q3"
            dt.Columns.Add(column)

            column = New DataColumn
            column.DataType = System.Type.GetType("System.Int32")
            column.ColumnName = Now.Year - i & "-Q2"
            dt.Columns.Add(column)

            column = New DataColumn
            column.DataType = System.Type.GetType("System.Int32")
            column.ColumnName = Now.Year - i & "-Q1"
            dt.Columns.Add(column)
        Next i
    End With
4

1 回答 1

3

由于您的前两列没有破折号,请尝试将它们过滤掉:

For Each columnQuarter As DataColumn In dt.Columns
  Dim s As String = columnQuarter.ColumnName
    If s.Contains("-") Then
      Dim words As String() = s.Split("-")
      Dim Year As String = words(0)
      Dim Quarter As String = words(1)
      Debug.WriteLine(Year)
      Debug.WriteLine(Quarter)
    End If
Next
于 2013-02-01T15:26:37.743 回答