简体   繁体   中英

PasteSpecial VBA with format and range

Hi I have the following Code:

Sub test()
    Dim objData As DataObject ' Set a reference to MS Forms 2.0
    Dim sHTML As String
    Dim sSelAdd As String
    Dim rng As Range

    Cells(2, 7).Value = Cells(2, 7).Value 
    Set rng = ActiveSheet.Cells(2, 7)

    Set objData = New DataObject
    sHTML = rng.Text
    objData.SetText sHTML
    objData.PutInClipboard
    ActiveSheet.PasteSpecial Format:="Unicode Text"
End Sub

However I was wondering if there is a way to use this method:

ActiveSheet.PasteSpecial Format:="Unicode Text"

In some sort of a way where I define the Paste range as well. It seems the text which is being pasted is copied in multiple cells overwriting other ones.

You could paste it to the currently selected cell, which can be very intuitive and useful for the end user:

Selection.PasteSpecial Format:="Unicode Text"

If you want to define the location in the code then you could do something like this:

Range("A1").PasteSpecial Format:="Unicode Text"

Edit: Today I learned that Range.PasteSpecial is different from Worksheet.PasteSpecial.

It looks like you can choose where you want to paste the data by selecting the cell before attempting to paste. This appears to do the trick for me:

Sub test()
    Dim objData As DataObject ' Set a reference to MS Forms 2.0
    Dim sHTML As String
    Dim sSelAdd As String
    Dim rng As Range

    Cells(2, 7).Value = Cells(2, 7).Value 
    Set rng = ActiveSheet.Cells(2, 7)

    Set objData = New DataObject
    sHTML = rng.Text
    objData.SetText sHTML
    objData.PutInClipboard
    rng.Select '<----Add this line.
    ActiveSheet.PasteSpecial Format:="Unicode Text"
End Sub

I found this to work:

Private Sub Worksheet_Activate()
 Dim objData As DataObject ' Set a reference to MS Forms 2.0
    Dim sHTML As String
    Dim sSelAdd As String
    Dim rng As Range

    Cells(1, 7).Value = Cells(1, 7).Value
    Set rng = ActiveSheet.Cells(1, 7)

    Set objData = New DataObject
    sHTML = rng.Text
    objData.SetText (sHTML)
    objData.PutInClipboard
    rng.Select
   Worksheets("GridData").Range("G1").Select
    ActiveSheet.PasteSpecial Format:= _
 "Unicode Text"
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM