Recently I started getting the error 1004: PasteSpecial method of Range class failed. I know people have said before that it might be that it is trying to paste to the active sheet when there is none, however, as you can see, everything is based on ThisWorkbook so that shouldn’t be the problem. It happens extra much when Excel doesn’t have the focus.
'references the Microsoft Forms Object Library
Sub SetGlobals()
Set hwb = ThisWorkbook' home workbook
Set mws = hwb.Worksheets("Code Numbers") ' main worksheet
Set hws = hwb.Worksheets("Sheet3") ' home worksheet (Scratch pad)
Set sws = hwb.Worksheets("Status") ' Status sheet
Set aws = hwb.Worksheets("Addresses") ' Addresses sheet
End Sub
Sub Import()
Call SetGlobals
hws.Select
'a bunch of code to do other stuff here.
For Each itm In itms
Set mitm = itm
body = Replace(mitm.HTMLBody, "<img border=""0"" src=""http://www.simplevoicecenter.com/images/svc_st_logo.jpg"">", "")
Call Buf.SetText(body)
Call Buf.PutInClipboard
Call hws.Cells(k, 1).Select
Call hws.Cells(k, 1).PasteSpecial
For Each shape In hws.Shapes
shape.Delete
Next shape
'Some code to set the value of k
'and do a bunch of other stuff.
Next itm
End Sub
Update: mitm and itm have two different types, so I did it for intellisense and who knows what else. This code takes a list of emails and pastes them into excel so that excel parses the html (which contains tables) and pastes it directly into excel. Thus the data goes directly into the sheet and I can sort it and parse it and whatever else I want.
I guess I’m basically asking for anyone who knows another way to do this besides putting it in an html file to post it. Thanks
This probably will not exactly answer your problem – but I noticed a few things in your source code that are too long to place in a comment, so here it is. Some of it is certainly because you omitted it for the example, but I’ll mention it anyway, just in case:
Option Explicit– this will avoid a lot of errors as it forces you to declare every variableCall SetGlobalscan be simplified toSetGlobals– same forCall Buf.SetText(body)=Bof.SetText Body, etc.hws.Select,hws.Cells(k,1).Select)Set mitm = itm?mitmwill therefore be the same object asitm– so you can simply useitmhwsmultiple times – for each element initms. However, once is enough, so move the delete loop outside of the For Each loophws.Cells(k, 1).Value = body– this should solve your error!Sheet1 (sheetname),Sheet2 (sheetname), etc.. You can rename these objects – go to their properties (F4) and change it to meaningful names – or your current names (hwb,mws, …) if you want. Then you can access them throughout your code without any assignment! And it’ll work later, even if you change the name ofSheet3to something meaningful! 😉Thus, taking it all into account, I end up with the following code, doing the same thing: