【发布时间】:2017-02-08 10:03:35
【问题描述】:
我有一个宏,可以将剪贴板中的多行数据粘贴到选定的单元格中。它将为每一行插入新行。列 A 和 Row1 包含标题,它将为任何插入的行填充它。
Sheet1
Header0 Header Header Header
Header1 Data
Header2 Data Data1
Data2 Data
Header3 Data
有时它会添加额外的 "" 引号,有时则不会。有没有办法在不删除合法引号字符的情况下清理剪贴板数据?
Sub ClipboardToRows()
' Split multi-lined data into separate rows for the current selection
' Assumption is that Column A contains row headers
Dim currRange As Range, currCell As Range, pasteCell As Range
Dim rowHeader As String
Dim cellContent
Dim cellStr
Dim clipboard As MSForms.DataObject
Dim str1 As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
On Error GoTo clipEmpty
str1 = Trim(clipboard.GetText())
Application.CutCopyMode = False
Set currCell = Selection
rowHeader = Cells(currCell.Row, 1).Value
'Skip Column A
If (currCell.Column > 1) Then
cellContent = Split(str1, Chr(10))
For i = LBound(cellContent) To (UBound(cellContent))
cellStr = Trim(cellContent(i))
If Len(cellStr) > 0 Then
Set pasteCell = currCell.Offset(i)
'Set current cell with line 1
If i = 0 Then
currCell.Value = cellContent(i)
Else
'If next cell down is not empty or the row header is different
If (Not IsEmpty(pasteCell.Value)) Or (Cells(pasteCell.Row, 1).Value <> rowHeader) Then
pasteCell.EntireRow.Insert
Cells(pasteCell.Row - 1, 1).Value = rowHeader
End If
currCell.Offset(i).Value = cellContent(i)
End If
End If
Next
End If
clipEmpty:
If Err <> 0 Then MsgBox "There was an issue with pasting. Please try again."
End Sub
【问题讨论】:
-
可能不是完全重复,但相关:stackoverflow.com/q/24910288/4996248
-
谢谢,我正在查看,但就我而言,我正在复制的来源可能来自任何地方,而不仅仅是 Excel 单元格。所以我只想获取剪贴板的内容(假设用户已经在某些东西上按了 CTRL+C)。
标签: vba excel clipboard clipboarddata