Vba paste ошибка

I am sorry as this has been probbably discussed many time here. I have got following problem. This macro should paste from clipboard to cells(1,1). And if there is no data in clipboard, I would like it to display msgbox with test «Nothing to paste».

What this keep doing is on error it will enter in cell(1,1) text: «MsgBox «Nothing to paste»» instead of displaying message.

Could you please help me correct mistake? Many thanks in advance!!!

Sub Paste()

Cells(1, 1).PasteSpecial

If Err Then
MsgBox "Nothing to paste"
End If

End Sub

asked Mar 28, 2014 at 12:26

Petrik's user avatar

1

Try clearing the clipboard after you paste your text so that the next run wont contain the same text that was just pasted.

Sub Paste()
    On Error Resume Next
    Cells(1, 1).PasteSpecial

    'Clear clipboard
    Application.CutCopyMode = False

    If Err Then
        MsgBox "Nothing to paste!"
        Err.Clear
    End If
End Sub

Here is another way that uses the MS clipboard more directly. First you need to add a reference to: Microsoft Forms 2.0 Object Library in your vba project.

Public Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function EmptyClipboard Lib "user32" () As Long
Public Declare Function CloseClipboard Lib "user32" () As Long

Sub Paste()
    Dim DataObj As New MSForms.DataObject
    DataObj.GetFromClipboard

    On Error GoTo ErrorHandler
        ActiveSheet.Cells(1, 1).Value = DataObj.GetText

        OpenClipboard (0&)
        EmptyClipboard
        CloseClipboard
        Exit Sub

ErrorHandler:
    MsgBox "Nothing to paste!"
End Sub

answered Mar 28, 2014 at 12:45

Automate This's user avatar

Automate ThisAutomate This

30.8k11 gold badges60 silver badges82 bronze badges

4

Sub Paste()
    On Error Resume Next
    Cells(1, 1).PasteSpecial

    'Clear clipboard
    Application.CutCopyMode = False

    If Err Then
       MsgBox "Nothing to paste!"
       Err.clear
    End If
End Sub

now it is working perfectly, I’ve changed .Paste to .PasteSpecial

answered Mar 28, 2014 at 13:58

Petrik's user avatar

PetrikPetrik

8232 gold badges12 silver badges25 bronze badges

I need some advice to rectify the code below. I have this code to copy paste lines to another sheet for data compilation purpose. And I’m running well using the with statement below, the problem is, when there’s no data to paste, I do not know how to end the code with message box.
I see the similar question above, but how to comply the code into the With statement of VBA below?

Following is the code I read from other user, to return message box if error.
If Err Then
MsgBox «Nothing to paste!»
Err.Clear
End If

My original code, without the Message box return.

*Sub FnLstRow()
Application.ScreenUpdating = False
Dim LR As Long
ThisWorkbook.Worksheets("Data").Select
LR = Cells(Rows.Count, "AO").End(xlUp).Row
Cells(LR, 1).Offset(1, 0).EntireRow.Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
With Sheets("LatestData")
    .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues

End With
Application.CutCopyMode = False


Range("A1").Select
Application.ScreenUpdating = True
End Sub**

Following extensive hours of online research and code compilation, I have managed to develop a functional piece of code. Unfortunately, this code is not capable of retrieving values from other sheets. Upon testing, I have experienced a messagebox error even when test data is present. My objective was to design a macro that cross-references data from one sheet with multiple other sheets in the same workbook.

Table of contents

  • VBA Paste and on Error display msgbox
  • Syntax error with simple MsgBox
  • VBA runtime error 13 using Msgbox
  • What is MsgBox in Excel VBA?
  • How to use VBA on Error goto error message?
  • What is the use of VBA on error?
  • What is a VBA message box title?

VBA Paste and on Error display msgbox


Question:

Apologies if this has been discussed before, but I am encountering an issue where a macro needs to paste data from the clipboard into cells(1,1). However, if the clipboard is empty, I want it to display a message box that says «Nothing to paste».

Instead of displaying a message, in case of an error, it will enter the text «MsgBox «Nothing to paste»» in cell (1,1).

Would you kindly assist me in rectifying an error? Your help is greatly appreciated in advance.

Sub Paste()
Cells(1, 1).PasteSpecial
If Err Then
MsgBox "Nothing to paste"
End If
End Sub


Solution 1:

In order to prevent the repetition of previously pasted text, it is advisable to clear the clipboard after pasting your text.

Sub Paste()
    On Error Resume Next
    Cells(1, 1).PasteSpecial
    'Clear clipboard
    Application.CutCopyMode = False
    If Err Then
        MsgBox "Nothing to paste!"
        Err.Clear
    End If
End Sub

Another approach involves utilizing the MS clipboard in a more direct manner. To implement this method, you must first incorporate a reference to the «Microsoft Forms 2.0 Object Library» within your vba project.

Public Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function EmptyClipboard Lib "user32" () As Long
Public Declare Function CloseClipboard Lib "user32" () As Long
Sub Paste()
    Dim DataObj As New MSForms.DataObject
    DataObj.GetFromClipboard
    On Error GoTo ErrorHandler
        ActiveSheet.Cells(1, 1).Value = DataObj.GetText
        OpenClipboard (0&)
        EmptyClipboard
        CloseClipboard
        Exit Sub
ErrorHandler:
    MsgBox "Nothing to paste!"
End Sub


Solution 2:

Sub Paste()
    On Error Resume Next
    Cells(1, 1).PasteSpecial
    'Clear clipboard
    Application.CutCopyMode = False
    If Err Then
       MsgBox "Nothing to paste!"
       Err.clear
    End If
End Sub

It is now functioning flawlessly after modifying the code from .Paste to .PasteSpecial.

Messagebox in vba Code Example, MsgBox «My Message», vbYesNo/vbMsgBox, «My Title» “messagebox in vba” Code Answer. message box VBA

Syntax error with simple MsgBox


Question:

enter image description here

At work, I am solely operating the
learning VBA
program.

Attached herewith is a snapshot of the syntax error.

I repeatedly encounter an error when the msgbox is triggered.

What did I do wrong?

Private Sub CommandButton1_Click()
Dim firstnum, secondnum As Single
firstnum = Cells(1, 1).Value
secondnum = Cells(1, 2).Value
If firstnum > secondnum Then
MsgBox " The first number is greater than the second number"
If firstnum < secondnum Then
MsgBox " The first number is less than the second number"
Else
MsgBox " They are euqal "
End If
End Sub


Solution:

To test your program, I introduced some modifications. Upon observation, I found that you have used two

if

statements without closing the second one. It is recommended to have an

end if

statement for each

if

. Additionally, I believe you could do without two

if

statements and instead use the

elseif

statement.

Private Sub test()
Dim firstnum, secondnum As Single
 firstnum = Cells(1, 1).Value
 secondnum = Cells(1, 2).Value
If firstnum > secondnum Then
 MsgBox " The first number is greater than the second number"
ElseIf firstnum < secondnum Then
 MsgBox " The first number is less than the second number"
Else
 MsgBox " They are euqal "
End If
End Sub

It is recommended to consistently use indentation as a tip.

On error along with message box in VBA, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more Code sampleWhoa:MsgBox Err.DescriptionEnd SubPublic Function FileFolderExists(strFullPath As String) As BooleanOn Error GoTo EarlyExitFeedback

VBA runtime error 13 using Msgbox


Question:

My knowledge of VBA is at a basic level as I am still very new to it.

My attempt is to design a macro that can cross-check
cross-reference
entries on a single sheet with several other sheets in the identical workbook. Whenever a match is discovered, an alert message box must pop up to inform the user about the location of the data.

This is what I have after spending countless hours sifting through the internet and assembling fragments of code.

Sub search()
Dim ws As Worksheet, found As Range
Dim TextToFind(1 To 20) As String
Dim iText As Long
TextToFind(1) = "Jade Smith"
TextToFind(2) = "Bob Collins"
TextToFind(3) = "Jemima Smythe"
For Each ws In ThisWorkbook.Worksheets
    With ws
        If .Name <> "Blacklisted Candidates" Then 'Do not search blacklist candidates!
            iText = 1
            Do While iText <= UBound(TextToFind)
                If TextToFind(iText) <> "" Then 'Do not search blank strings!
                    Set found = .UsedRange.Find(what:=TextToFind(iText), LookIn:=xlformulas, LookAt:=xlPart, MatchCase:=False)
                    If Not found Is Nothing Then
                        MsgBox "Proxy Candidate Found at " & found.Address
                    Else
                        MsgBox "No Proxy Candidates Found ", vbOKOnly, "Success!"
                    End If
                    iText = iText + 1
                End If
            Loop
        End If
   End With
Next ws
End Sub

However, this code is unable to retrieve values from sheets other than the current one.

Upon testing, the message box displays even in the absence of data, despite the presence of test data.

I possess a workbook that comprises of nearly nine sheets, with an ever-expanding nature. My aim is to examine the first nine columns of each sheet to seek the desired data. I have manually fed the macro with the data to look for, but to no avail, as the macro does not return any results despite the presence of the data.


Solution 1:

It seems like you are attempting to apply the binary operator

And

to two strings, when you likely intended to use

&

to join the strings together.

Documentation :


  • And

  • &

The documentation is applicable to both languages, VB.Net and the other one, without any difference in functionality.

So to fix it, replace

MsgBox ("Proxy Candidate Found at " And rngX.Address)

By

MsgBox ("Proxy Candidate Found at " & rngX.Address)


Solution 2:

Adjusted to accommodate the search within a cell that obtains its content from a formula.

To summarize the comments and the answer from litelite, and provide my input, here is a functional code.

Option Explicit
Sub search()
    Dim ws As Worksheet, found As Range
    Dim TextToFind(1 To 20) As String
    Dim iText As Long
    TextToFind(1) = "xxxx"
    TextToFind(2) = "xxxx"
    TextToFind(3) = "xxxxx"
    For Each ws In ThisWorkbook.Worksheets
        With ws
            If .name <> "Blacklisted Candidates" Then 'Do not search blacklist candidates!
                iText = 1
                Do While iText <= UBound(TextToFind)
                    If TextToFind(iText) <> "" Then 'Do not search blank strings!
                        Set found = .UsedRange.Find(what:=TextToFind(iText), LookIn:=xlFormulas, LookAt:=xlPart, MatchCase:=False)
                        If Not found Is Nothing Then
                            MsgBox "Proxy Candidate Found at " & found.Address
                        Else
                            MsgBox "No Proxy Candidates Found ", vbOKOnly, "Success!"
                        End If
                        iText = iText + 1
                    End If
                Loop
            End If
       End With
    Next ws
End Sub

Understanding what response codes come back from, Basically, you could rewrite the code to this: Dim message As Integer message = MsgBox («Click Yes to Proceed, No to stop», vbYesNoCancel, «Login») If message = MsgBoxResult.Yes Then Range («A1»).Value = «You may proceed» ActiveWorkbook.Activate ElseIf message = MsgBoxResult.No Then …


  • #1

Gentlemen

If a line in VBA says: «ActiveSheet.Paste» and the ClipBoard is empty, the program crashes with a, [Run-time error ‘1004’:
Paste method of Worksheet class failed]
Error message.

Does anyone know how to test for an empty ClipBoard in VBA?

By the Way, Maslan asked a similar question here:

Clipboard Oddities

Thnaks

StACase@mailcity.com

Last edited by a moderator:

Round to nearest half hour?

Use =MROUND(A2,»0:30″) to round to nearest half hour. Use =CEILING(A2,»0:30″) to round to next half hour.

  • #2

Something like this may help….change
as required….

<pre/>
On Error Resume Next
ActiveSheet.Paste
If Err Then MsgBox «Nothing to paste!»: Err.Clear
</pre>

  • #3

Thank you

Plugged that baby in, and it worked first time out of the box! WooHoo!

The user is happy too :)

  • #4

This code is exactly what I need but I’m fairly inexperienced with the use of Message Boxes so need some more help please.

This is my ‘paste’ code

Sub PasteData()

‘ PasteData Macro

Application.ScreenUpdating = False
Range(«B1»).Select
ActiveSheet.PasteSpecial Format:=»Text», Link:=False, DisplayAsIcon:= _
False
Cells.Columns.AutoFit
Application.ScreenUpdating = True
End Sub

When I try to paste with an empty clipboard the error described in the first post appears.

I tried adding the suggested code to my VBA but when I run the macro the following text just gets pasted into cell B1.

If Err Then MsgBox «Nothing to paste!»: Err.Clear

Do I have to add a message box by some other means?

Thanks

Nick

  • #6

That’s probably because you still had If Err Then MsgBox «Nothing to paste!»: Err.Clear in the clipboard when you ran the macro, so it did exactly what you told it to do: paste the contents of the clipboard into B1.

Your code should look like this:-

Code:

[FONT=Courier New]Sub PasteData()[/FONT]
[FONT=Courier New]'[/FONT]
[FONT=Courier New]' PasteData Macro[/FONT]
[FONT=Courier New]'[/FONT]
[FONT=Courier New]  Application.ScreenUpdating = False[/FONT]
[FONT=Courier New]  Range("B1").Select[/FONT]
[FONT=Courier New][COLOR=red][B]  On Error Resume Next[/B][/COLOR][/FONT]
[FONT=Courier New]  ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= False[/FONT]
[FONT=Courier New][COLOR=red][B]  If Err Then MsgBox "Nothing to paste!": Err.Clear[/B][/COLOR][/FONT]
[FONT=Courier New]  Cells.Columns.AutoFit[/FONT]
[FONT=Courier New]  Application.ScreenUpdating = True[/FONT]
[FONT=Courier New]End Sub[/FONT]

To test the On Error clause, make sure your clipboard is empty and then run it: the message box will appear.

You’ve already tested it with the clipboard not empty!

  • #7

That’s probably because you still had If Err Then MsgBox «Nothing to paste!»: Err.Clear in the clipboard when you ran the macro, so it did exactly what you told it to do: paste the contents of the clipboard into B1.

Your code should look like this:-

Code:

[FONT=Courier New]Sub PasteData()[/FONT]
[FONT=Courier New]'[/FONT]
[FONT=Courier New]' PasteData Macro[/FONT]
[FONT=Courier New]'[/FONT]
[FONT=Courier New]  Application.ScreenUpdating = False[/FONT]
[FONT=Courier New]  Range("B1").Select[/FONT]
[FONT=Courier New][COLOR=red][B]  On Error Resume Next[/B][/COLOR][/FONT]
[FONT=Courier New]  ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= False[/FONT]
[FONT=Courier New][COLOR=red][B]  If Err Then MsgBox "Nothing to paste!": Err.Clear[/B][/COLOR][/FONT]
[FONT=Courier New]  Cells.Columns.AutoFit[/FONT]
[FONT=Courier New]  Application.ScreenUpdating = True[/FONT]
[FONT=Courier New]End Sub[/FONT]

To test the On Error clause, make sure your clipboard is empty and then run it: the message box will appear.

You’ve already tested it with the clipboard not empty!

D’oh.

Cheers dude.

  • #8

Code:

Private Declare PtrSafe Function CountClipboardFormats Lib "user32" () As Long

Function IsClipboardEmpty() As Boolean
    IsClipboardEmpty = (CountClipboardFormats() = 0)
End Function

Function IsClipboardEmpty2() As Boolean
IsClipboardEmpty2 = Application.CommandBars.FindControl(Id:=22).Enabled
'or:
'= (Application.ClipboardFormats(1) = -1) '??
End Function

Хитрости »

28 Март 2018              7066 просмотров


Ничто в мире не идеально, и Excel тоже. Как и любая программа он порой может сильно удивлять разными «непонятками». Вот очередная шутка: казалось бы простой код по копированию и вставке картинки из листа Excel, который отлично работает в 2010, вылетает в 2016 с ошибкой Метод paste из класса worksheet завершен неверно:
Ошибка при вставке картинки
Сам код простой и ошибки в общем-то вызывать не должен:

Sub CopyPastePicture()
    ActiveWorkbook.Sheets("PICS").Shapes("Picture1").Copy
    ActiveWorkbook.Sheets("MAIN").Paste
End Sub

При этом самое печально то, что это даже не на каждом ПК проявляется. А при пошаговой отладке кода и вовсе пропадает. Т.е. для получения ошибки недостаточно одного Excel 2016, здесь влияет несколько факторов: установленные программы, операционная система, метод выполнения и т.д. и т.п. Разбирать каждый частный случай не представляется возможным. Да и даже если найти причину — что, теперь надо удалять все лишнее, что не понравилось Excel-ю? А почему тогда это лишнее не мешает тому же коду в Excel 2010? А если этот код — часть программы на заказ? Заказчик скажет «Тыжпрограммист» и будет прав — это наша проблема, проблема разработчиков. Мы обязаны знать эти подводные камни или как минимум хоть уметь вовремя их устранять. Поэтому приходится искать обходные пути. Судя по ошибке, сам корень зла где-то по пути от буфера к Excel. Возможно, наша скопированная картинка просто не до конца «прогрузилась» в буфер и надо дождаться завершения этой прогрузки. Текст ошибки несколько укрепляет это предположение. Первый порыв — использовать DoEvents, чтобы передать эстафету операционной системе — дать ей завершить свои процессы, в том числе и обработку буфера обмена:

Sub CopyPastePicture()
    ActiveWorkbook.Sheets("PICS").Shapes("Picture1").Copy
    DoEvents
    ActiveWorkbook.Sheets("MAIN").Paste
End Sub

Но это не спасает ситуацию. Равно как не спас и цикл с сотней DoEvents:

Sub CopyPastePicture()
    Dim i As Long
    ActiveWorkbook.Sheets("PICS").Shapes("Picture1").Copy
    For i = 1 To 100: DoEvents: Next
    ActiveWorkbook.Sheets("MAIN").Paste
End Sub

С одной стороны все логично и должно работать. И даже работает, но не всегда — ошибка все равно появлялась чуть ли не в половине случаев. Почему? Потому что дело все же в некорректной работе буфера. И DoEvents хоть и передавал управление — проблемы вовсе не решал. Он просто давал небольшую отсрочку, которая позволяла в ряде случаев картинке догрузиться в буфер и избежать ошибки. Но главная проблема в том, что неизвестно для какого ПК сколько таких циклов надо, потому что неизвестно сколько ждать до полной загрузки картинки в буфер. Неизвестно, т.к. на каждом ПК это может быть разное время. В итоге, помучившись еще какое-то время я нашел «костыльное» решение проблемы через такой код:

Sub CopyPastePicture()
    'сначала очистим буфер, чтобы там точно ничего лишнего не было
    Application.CutCopyMode = False
    'копируем картинку
    ActiveWorkbook.Sheets("PICS").Shapes("Picture1").Copy
    'а теперь разрешаем пропуск всех ошибок!
    On Error Resume Next
    Err.Clear 'очищаем лог ошибок, если они были
    'пробуем вставить нашу картинку
    ActiveWorkbook.Sheets("MAIN").Paste
    'если в момент вставки возникла ошибка
    '    сработает цикл, который будет выполняться до тех пор,
    '    пока что-то все же не вставится
    Do While Err.Number <> 0
        Err.Clear
        ActiveWorkbook.Sheets("MAIN").Paste
        'передаем управление системе
        DoEvents
    Loop
    'отключаем пропуск ошибок
    On Error GoTo 0
    'опять очищаем буфер - теперь уже от того, что скопировали сами кодом
    Application.CutCopyMode = False
End Sub

Решение основано на том, что мы сначала копируем картинку, а потом пробуем её вставить. Если возникает ошибка — запускаем цикл, в котором пытаемся вставить картинку из буфера до тех пор, пока она все же не будет вставлена. Т.е. пока ошибка возникает — картинка не прогрузилась и цикл работает. Как только картинка прогрузилась в буфер — она вставляется без ошибки и цикл завершается.
И такой подход работает и по скорости не сильно тормозит процесс. Единственное, что неплохо было бы добавить — так это некий счетчик. Вдруг по какой-то причин буфер вообще очистился(ну бывают системные ошибки) или ошибка возникала совсем по другой причине(например, вставка производится на защищенный лист) — тогда получим бесконечный цикл. В этом случае лучше всего код «обернуть» в функцию:

'---------------------------------------------------------------------------------------
' Author : The_Prist(Щербаков Дмитрий)
'          http://www.excel-vba.ru
'          info@excel-vba.ru
' Purpose: Копирует указанную картинку и вставляет на заданный лист
'          oCopy    - картинка, для вставки на лист
'          wsPaste  - лист, на который необходимо вставить картинку
'---------------------------------------------------------------------------------------
Function CopyPastePicture(oCopy As Shape, wsPaste As Worksheet)
    Dim lPasteCnt As Long 'счетчик вставок
    'сначала очистим буфер, чтобы там точно ничего лишнего не было
    Application.CutCopyMode = False
    'копируем картинку
    oCopy.Copy
    'а теперь разрешаем пропуск всех ошибок!
    On Error Resume Next
    Err.Clear 'очищаем лог ошибок, если они были
    'пробуем вставить нашу картинку
    wsPaste.Paste
    'если в момент вставки возникла ошибка
    '    сработает цикл, который будет выполняться до тех пор,
    '    пока что-то все же не вставиться
    Do While Err.Number <> 0
        Err.Clear
        wsPaste.Paste
        'передаем управление системе
        DoEvents
        'сччитаем кол-во вставок
        lPasteCnt = lPasteCnt + 1
        'если уже более 1000 вставок сделали
        '  но ошибка не уходит - принудительно завершаем цикл
        '  ошибка при этом будет не нулевой
        If lPasteCnt > 1000 Then
            Exit Do
        End If
    Loop
    'если вставка прошла успешно - ошибка будет нулевой
    CopyPastePicture = (Err.Number = 0)
    'отключаем пропуск ошибок
    On Error GoTo 0
    'опять очищаем буфер - теперь уже от того, что скопировали сами кодом
    Application.CutCopyMode = False
End Function

тогда можно будет не только вставить картинку, но и получить обратную связь — успешно прошла вставка или нет. Если кажется, что 1000 попыток это много, то можно просто в строке If lPasteCnt > 1000 Then вместо 1000 указать нужное число.
А использовать приведенную функцию можно будет так:

Sub TryPastePicture()
    If CopyPastePicture(ActiveWorkbook.Sheets("PICS").Shapes("Picture1"), ActiveWorkbook.Sheets("MAIN")) = False Then
        MsgBox "Не удалось вставить картинку", vbInformation, "www.excel-vba.ru"
        Exit Sub
    End If
End Sub

Т.е. мы вызываем функцию, которая пробует вставить картинку. Если все 1000 попыток были безуспешными, то функция вернет значение False. Если же хоть одна вставка удалась — функция вернет True.
Кстати, функция поможет сделать вставку не только картинки, но и любой другой фигуры, у которой есть метод Copy: рисунок, фигура, диаграмма.

Если тоже столкнулись с такой проблемой — делитесь в комментариях кто как решал и что помогло. Соберем подборку методов :)


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

Понравилась статья? Поделить с друзьями:
  • Vba excel ошибка знач
  • Valheim вылетает ошибка unity
  • Valeo thermo e320 сброс ошибок
  • Valeo thermo 350 коды ошибок
  • Val1 ошибка валорант