GetFormat、GetText、SetText 方法範例

以下範例使用 GetFormat、 GetText 和 SetText 方法,在 DataObject 與剪貼簿之間傳輸文字。

使用者在 文字框 中輸入文字,然後點擊 CommandButton1 即可將文字以標準文字格式傳輸到 資料物件 。

點擊 CommandButton2 可從 DataObject 取得文字。

點擊 CommandButton3 可將 TextBox1 的文字以自訂格式複製到 DataObject 。

點擊 CommandButton4 可從 DataObject 中取得自訂格式的文字。

若要使用本範例,請將此範例程式碼複製到表單的宣告部分中。 請確定該表單包含:

  • 一個名為 TextBox1 的 TextBox 。
  • 四個 CommandButton 控制項分別從 CommandButton1 到 CommandButton4。
  • 一個名為 Label1 的 Label 。
Dim MyDataObject As DataObject 
 
Private Sub CommandButton1_Click() 
'Put standard format on Clipboard 
 If TextBox1.TextLength > 0 Then 
 Set MyDataObject = New DataObject 
 MyDataObject.SetText TextBox1.Text 
 Label1.Caption = "Put on D.O." 
 CommandButton2.Enabled = True 
 CommandButton4.Enabled = False 
 End If 
End Sub 
 
Private Sub CommandButton2_Click() 
'Get standard format from Clipboard 
 If MyDataObject.GetFormat(1) = True Then 
 Label1.Caption = "Std format - " _ 
 & MyDataObject.GetText(1) 
 End If 
End Sub 
 
Private Sub CommandButton3_Click() 
'Put custom format on Clipboard 
 If TextBox1.TextLength > 0 Then 
 Set MyDataObject = New DataObject 
 MyDataObject.SetText TextBox1.Text, 233 
 Label1.Caption = "Custom on D.O." 
 CommandButton4.Enabled = True 
 CommandButton2.Enabled = False 
 End If 
End Sub 
 
Private Sub CommandButton4_Click() 
'Get custom format from Clipboard 
 If MyDataObject.GetFormat(233) = True Then 
 Label1.Caption = "Cust format - " _ 
 & MyDataObject.GetText(233) 
End If 
End Sub 
 
Private Sub UserForm_Initialize() 
 CommandButton2.Enabled = False 
 CommandButton4.Enabled = False 
End Sub

支援和意見反應

有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應。