我正在尝试拆分字符串并获取拆分部分并将它们分配给变量。这适用于第一个变量,但我无法使第二个变量起作用。
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。
其他信息:
以下是我用于将列添加到dataTable的代码。正如您所看到的,我的前两列不包含“ - ”。
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
答案 0 :(得分: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