Function pasteExcel(ByVal DGV As DataGridView)
Try ' 目前單元格是否選擇的判斷
If DGV.CurrentCell Is Nothing Then
Return (0)
End If
If DGV.Rows.Count = 1 Then
DGV.Rows.Add("", "")
DGV.CurrentCell = DGV.Item(0, 0)
End If
Dim insertRowIndex As Integer = DGV.CurrentCell.RowIndex
' 擷取剪切闆的内容,并按行分割
Dim pasteText As String = Clipboard.GetText()
If String.IsNullOrEmpty(pasteText) Then
Return (0)
End If
pasteText = pasteText.Replace(vbCrLf, vbLf)
pasteText = pasteText.Replace(vbCr, vbLf)
pasteText.TrimEnd(New Char() {vbLf})
Dim lines As String() = pasteText.Split(vbLf)
Dim cell As String()
ReDim Preserve lines(lines.Length - 2) '防止粘貼後出現空白
For i As Integer = 0 To lines.Length - 1
cell = lines(i).Split(ControlChars.Tab)
For o = 0 To cell.Length - 1
If DGV.CurrentCell.ColumnIndex + o > DGV.Columns.Count - 1 Then DGV.Columns.Add("", "")
If DGV.CurrentCell.RowIndex + i > DGV.Rows.Count - 2 Then DGV.Rows.Add("", "")
DGV.Item(DGV.CurrentCell.ColumnIndex + o, DGV.CurrentCell.RowIndex + i).Value = cell(o)
Next
Next
If DGV.CurrentCell.ColumnIndex = 0 Then
Dim rtn& = MsgBox("檢測到此次粘貼的目标位置處于表的第一行,是否需要将粘貼内容的第一行放入列标題?", MsgBoxStyle.YesNo, "提示!")
If rtn = MsgBoxResult.Yes Then
For i As Integer = 0 To DGV.Columns.Count - 1
For o As Integer = 0 To DGV.Rows.Count - 2
DGV.Rows.Item(o).HeaderCell.Value = Str(o + 1)
If o = 0 Then DGV.Columns.Item(i).HeaderText = DGV.Item(i, o).Value
DGV.Item(i, o).Value = DGV.Item(i, o + 1).Value
Next
Next
DGV.Rows.RemoveAt(DGV.Rows.Count - 2)
End If
End If
Return (0)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Return (0)
End Function '粘貼excel資訊