這是關於編輯器設置。當您在Excel中複製時,它會以幾種不同的格式將數據放入Windows剪貼板。其中一種格式是純文本格式,另一種格式是HTML格式,其中可能有一些專有的二進制格式。
當你在另一個應用程序中過去時,它具有它想要的格式的優先級。您的編輯器可能會首先查找HTML。如果有HTML格式,它會抓住它。如果複製的數據無法通過Windows剪貼板表示爲HTML,則編輯器可能會轉到列表中的#2格式 - 可能是純文本。
如果您想控制Excel表格如何轉換爲HTML,您必須自己動手。此代碼將Excel範圍轉換爲html表格。
Sub CopyRangeToHtmlTable()
Dim doClip As MSForms.DataObject
Dim vaTable As Variant
Dim i As Long, j As Long
Dim aTable() As String
Dim aRow() As String
'Read range into array
vaTable = Sheet1.Range("A1:B4").Value
'set up array to hold all of the rows
ReDim aTable(1 To UBound(vaTable, 1))
'loop through the rows
For i = LBound(vaTable, 1) To UBound(vaTable, 1)
'set up array to hold all of the tds
ReDim aRow(1 To UBound(vaTable, 2))
'loop through the tds
For j = LBound(vaTable, 2) To UBound(vaTable, 2)
aRow(j) = Tag(vaTable(i, j), "td")
Next j
'add the row to the table array
aTable(i) = Tag(Join(aRow, vbNullString), "tr")
Next i
'put the table into the clipboard
Set doClip = New MSForms.DataObject
doClip.SetText Tag(Join(aTable, vbNewLine), "table", , True)
doClip.PutInClipboard
End Sub
Public Function Tag(ByVal sValue As String, _
ByVal sTag As String, _
Optional sAttr As String = "", _
Optional bIndent As Boolean = False) As String
Dim sReturn As String
If Len(sAttr) > 0 Then
sAttr = Space(1) & sAttr
End If
If bIndent Then
sValue = vbTab & Replace(sValue, vbNewLine, vbNewLine & vbTab)
sReturn = "<" & sTag & sAttr & ">" & vbNewLine & sValue & vbNewLine & "</" & sTag & ">"
Else
sReturn = "<" & sTag & sAttr & ">" & sValue & "</" & sTag & ">"
End If
Tag = sReturn
End Function
當我粘貼到記事本,它出來像
<table>
<tr><td>Name</td><td>Number</td></tr>
<tr><td>Tom</td><td>1</td></tr>
<tr><td>Dick</td><td>2</td></tr>
<tr><td>Harry</td><td>3</td></tr>
</table>