对于每个...下一次迭代比应做的多?

时间:2019-05-18 05:10:25

标签: excel vb.net

如果我从excel复制由三个单元格组成的一行,其中单元格1、2和3中的值分别为A,B和C,则我希望loadDG datagrid中有一行结果。但是,我得到的是For Each ... Next循环的第二次迭代的第二行结果,即使从Excel复制了仅一行值,如第2列中缺少值所示。 / p>

请有人可以解释发生了什么吗?这是(下面的编辑,下面的评论)代码:

Public Class Form1

'Initialise the Datagrid
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    InitialiseLoadsDG()
End Sub

'Initialise Datagrid
Public Sub InitialiseLoadsDG()
    LoadsDG.Rows.Clear()
    LoadsDG.RowTemplate.Height = 20

    For i As Integer = 1 To 50
        LoadsDG.Rows.Add(i, "", "", "")
    Next

    LoadsDG.ClearSelection()
End Sub

'Paste copied values
Private Sub LoadsDG_KeyDown(sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles LoadsDG.PreviewKeyDown

    If e.Control And e.KeyCode = Keys.V Then
        Dim i As Integer = 0

        For Each copiedLine As String In Clipboard.GetText.Split(vbNewLine)
            LoadsDG.Rows(i).Cells(1).Value = copiedLine
            LoadsDG.Rows(i).Cells(2).Value = i
            i = i + 1
        Next
    End If

End Sub

End Class

这是我的期望:

        Column1 Column2 Column3 Column4
   Row1           ABC      0
   Row2            

这就是我得到的:

        Column1 Column2 Column3 Column4
   Row1           ABC      0
   Row2                    1

更新:按照Jimi的评论,我用于粘贴剪贴板内容的Sub按预期方式工作。该代码从复制的excel内容中删除了回车符(vbCr),换行符(vbLf)以及合并的回车符和换行符(vbCrLf),仅保留制表符描述的值。请注意,复制的excel内容的每一行在copyedCells数组中都占用一个单个元素(制表符描述)。其余代码仅将每个制表符描述的(vbTab)行拆分为单独的excel单元格值,然后将其粘贴到适当的loadDG datagrid单元格中。非常感谢所有回应。这是完成的代码:

'Paste copied values
Private Sub LoadsDG_KeyDown(sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles LoadsDG.PreviewKeyDown

    If e.Control And e.KeyCode = Keys.V Then

        Dim copiedCells() As String = Clipboard.GetText.Split(New String() {vbCr, vbLf, vbCrLf}, StringSplitOptions.RemoveEmptyEntries)

        Dim i As Integer = 0
        Dim ii As Integer = 1

        For Each rowOfCells As String In copiedCells

            For Each cellValue As String In rowOfCells.Split(vbTab)
                LoadsDG.Rows(i).Cells(ii).Value = cellValue
                ii = ii + 1
            Next

            i = i + 1
            ii = 1
        Next

    End If

End Sub

0 个答案:

没有答案