Run-time Error '438' using .PasteSpecial - vba

I am trying to create a simple Macro to copy data from a closed Excel file into the current one that I have open. So far I have created this
Sub CopyData()
Dim path As String
path = "C:\Users\sam\Coding\bk.xlsx"
Dim currentWb As Workbook
Set currentWb = ThisWorkbook
Dim openWb As Workbook
Set openWb = Workbooks.Open(path)
Dim openWs As Worksheet
Set openWs = openWb.Sheets("Sheet1")
currentWb.Activate
openWb.Activate
openWs.Range("A1:C2").Copy
currentWb.Range("A1").PasteSpecial
openWb.Close (False)
End Sub
But I get a RunTime Error 438 and upon debug it highlights the row "currentWb.Range("A1").PasteSpecial". I have search all over the place to find an answer but I haven't been successful. My question is, what am I missing?
Thank you in advance!

The problem is
currentWb.Range("A1").PasteSpecial
It should be
currentWb.Sheets("SomeSheet").Range("A1").PasteSpecial xlPasteAll
replace xlPasteAll with whatever you are trying.
Range object is not a part of Workbook but of Worksheet
Also you don't need to use .Activate. You code can be written as
Sub CopyData()
Dim path As String
Dim currentWb As Workbook, openWb As Workbook
Dim currentWs As Worksheet, openWs As Worksheet
path = "C:\Users\sam\Coding\bk.xlsx"
Set currentWb = ThisWorkbook
'~~> Change this applicable
Set currentWs = currentWb.Sheets("Sheet1")
Set openWb = Workbooks.Open(path)
Set openWs = openWb.Sheets("Sheet1")
openWs.Range("A1:C2").Copy
currentWs.Range("A1").PasteSpecial xlPasteValues
openWb.Close (False)
End Sub

Related

VBA copying from one excel sheet to another excel sheet?

I am basically copying one excel file sheet to a particular sheet of the excel file(same file as where I am writing the macro).I get the error- Run time error '9': Subscript out of range on the line WbTarget.Sheets("FPP").Range("A1:E654").PasteSpecial
I am not that good in VBA-any help please?
Sub XMLR()
Dim output As String
output = CreateObject("WScript.Shell").Exec("R CMD BATCH filepath.R").StdOut.ReadAll
Call XML
End Sub
Sub XML()
Dim wbTarget
Dim wbThis
Dim strName
Set wbThis = Workbooks.Open("file.xlsx")
wbThis.Activate
strName = ActiveSheet.Name
Set wbTarget = ActiveWorkbook
Application.CutCopyMode = False
wbThis.Sheets("Sheet1").Range("A1:E654").Copy
wbTarget.Sheets("FPP").Range("A1:E654").PasteSpecial
Application.CutCopyMode = False
wbTarget.Save
wbTarget.Close
wbThis.Close
Set wbTarget = Nothing
Set wbThis = Nothing
End Sub
Slightly confusing, but try this:
Sub XML()
Dim wbTarget As Workbook
Dim wbThis As Workbook
Dim strName As String
Set wbThis = Workbooks.Open("file.xlsx")
ThisWorkbook.Sheets("FPP").Range("A1:E654").Value = wbThis.Sheets("Sheet1").Range("A1:E654").Value
wbTarget.Save
wbTarget.Close
wbThis.Close
Set wbTarget = Nothing
Set wbThis = Nothing
End Sub
The issue here is that both WbTarget and WbThis refer to the same workbook.
You should change you declaration:
Set wbTarget = ActiveWorkbook
to
Set wbTarget = Application.ThisWorkbook

Import TXT to Excel (VBA) Error

I am trying to open a text file and copy and paste it into my Data Sheet. However i can't seem to make it work (I see an object required error). Any help please? Thank you
Sub Bam2()
Dim FilesToOpen
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim newSheet As Worksheet
Dim targetSheet As Worksheet, sourceSheet As Worksheet
Dim customerWorkbook As Workbook, targetWorkbook As Workbook
Set targetWorkbook = Application.Workbooks("Book1.xlsm")
Set targetSheet = targetWorkboook.Sheets("Data")
targetSheet.Range("A1:M5000").ClearContents
FilesToOpen = Application.GetOpenFilename(Title:="Text Files to Open")
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen, Format:=4)
wkbTemp.Sheets(1).Cells.Copy
targetSheet.Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = 0
wkbTemp.Close
End Sub
At a guess
Set targetWorkbook = Application.Workbooks("Book1.xlsm")
If you've just created a workbook it's called Book1 - it's not called Book1.xlsm unless you've actually saved it under that name. Try
Set targetWorkbook = Application.Workbooks("Book1")
It does work when doing this, but how do I select to copy just one column in a specific range, and not the whole file?
Sub Bam()
Dim FilesToOpen
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim newSheet As Worksheet
FilesToOpen = Application.GetOpenFilename(Title:="Text Files to Open")
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen, Format:=4)
wkbTemp.Sheets(1).Cells.Copy
Set newSheet = ThisWorkbook.Sheets("Data")
With newSheet
.PasteSpecial
End With
Application.CutCopyMode = False
wkbTemp.Close
End Sub

copying range end xl down pasting different Wb

I've got a macro recorder code (with select and activate) that I'm trying to simplify. It currently looks like this:
Windows("Stambestand.xlsm").Activate
Range("AA2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("Ijking document.xlsm").Activate
Range("B3").Select
ActiveSheet.Paste
As of recently I've started using variables and want to trim down the code. I'm thinking along these lines:
WbStambestand.WsStam.Range("AA2", Selection, Selection.End(xlDown)).Copy WbIjk.WsIjk.range("A1").paste
Workbooks("WbStambestand").Worksheets("WsStam").Range("AA2", Selection, Selection.End(xlDown)).Copy
However, these don't function. I'm hoping you guys can help me along. Much appreciated.
FYI, these are my variables (they are declared). The Ijk ones are the paste destination.
Dim WbStambestand, WbIjk As Workbook
Dim WsIjk, WsStam As Worksheet
Set WsIjk = ActiveSheet
Set WbIjk = ActiveWorkbook
Set WsIjk = ActiveSheet
Set WbIjk = ActiveWorkbook
Set WbStambestand = Workbooks.Open(stam)
Set WsStam = WbStambestand.Worksheets("stambestand")
Try this
Sub abc()
Dim WbStambestand As Workbook
Dim WbIjk As Workbook
Dim WsIjk As Worksheet
Dim WsStam As Worksheet
Dim LastRow As Long
Dim stam As String
stam = "C:\Users\Admin\Desktop\Stambestand.xlsm" ' path with complete file name with extension.
Set WsIjk = ActiveSheet
Set WbIjk = ThisWorkbook ' workbook which has current code
Set WbStambestand = Workbooks.Open(stam)
Set WsStam = WbStambestand.Worksheets("stambestand")
LastRow = WsStam.Range("AA2").End(xlDown).Row
WsStam.Range("AA2:AA" & LastRow).Copy WsIjk.Range("B3")
End Sub

Excel VBA: Copying multiple sheets into new workbook

I have an error message of 'Object Required' when I run this sub. I have a version for copying each specific sheet, which works fine, but this sub is for all sheets within the WB ie to copy each one's WholePrintArea and paste it into a new sheet in the new WB. Thanks...
Sub NewWBandPasteSpecialALLSheets()
MyBook = ActiveWorkbook.Name ' Get name of this book
Workbooks.Add ' Open a new workbook
NewBook = ActiveWorkbook.Name ' Save name of new book
Workbooks(MyBook).Activate ' Back to original book
Dim SH As Worksheet
For Each SH In MyBook.Worksheets
SH.Range("WholePrintArea").Copy
Workbooks(NewBook).Activate
With SH.Range("A1")
.PasteSpecial (xlPasteColumnWidths)
.PasteSpecial (xlFormats)
.PasteSpecial (xlValues)
End With
Next
End Sub
Try do something like this (the problem was that you trying to use MyBook.Worksheets, but MyBook is not a Workbook object, but string, containing workbook name. I've added new varible Set WB = ActiveWorkbook, so you can use WB.Worksheets instead MyBook.Worksheets):
Sub NewWBandPasteSpecialALLSheets()
MyBook = ActiveWorkbook.Name ' Get name of this book
Workbooks.Add ' Open a new workbook
NewBook = ActiveWorkbook.Name ' Save name of new book
Workbooks(MyBook).Activate ' Back to original book
Set WB = ActiveWorkbook
Dim SH As Worksheet
For Each SH In WB.Worksheets
SH.Range("WholePrintArea").Copy
Workbooks(NewBook).Activate
With SH.Range("A1")
.PasteSpecial (xlPasteColumnWidths)
.PasteSpecial (xlFormats)
.PasteSpecial (xlValues)
End With
Next
End Sub
But your code doesn't do what you want: it doesen't copy something to a new WB. So, the code below do it for you:
Sub NewWBandPasteSpecialALLSheets()
Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Set wb = ThisWorkbook
Workbooks.Add ' Open a new workbook
Set wbNew = ActiveWorkbook
On Error Resume Next
For Each sh In wb.Worksheets
sh.Range("WholePrintArea").Copy
'add new sheet into new workbook with the same name
With wbNew.Worksheets
Set shNew = Nothing
Set shNew = .Item(sh.Name)
If shNew Is Nothing Then
.Add After:=.Item(.Count)
.Item(.Count).Name = sh.Name
Set shNew = .Item(.Count)
End If
End With
With shNew.Range("A1")
.PasteSpecial (xlPasteColumnWidths)
.PasteSpecial (xlFormats)
.PasteSpecial (xlValues)
End With
Next
End Sub
Rethink your approach. Why would you copy only part of the sheet? You are referring to a named range "WholePrintArea" which doesn't exist. Also you should never use activate, select, copy or paste in your script. These make the "script" vulnerable to user actions and other simultaneous executions. In worst case scenario data ends up in wrong hands.
This worked for me (I added an "if sheet visible" because in my case I wanted to skip hidden sheets)
Sub Create_new_file()
Application.DisplayAlerts = False
Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Dim pname, parea As String
Set wb = ThisWorkbook
Workbooks.Add
Set wbNew = ActiveWorkbook
For Each sh In wb.Worksheets
pname = sh.Name
If sh.Visible = True Then
sh.Copy After:=wbNew.Sheets(Sheets.Count)
wbNew.Sheets(Sheets.Count).Cells.ClearContents
wbNew.Sheets(Sheets.Count).Cells.ClearFormats
wb.Sheets(sh.Name).Activate
Range(sh.PageSetup.PrintArea).Select
Selection.Copy
wbNew.Sheets(pname).Activate
Range("A1").Select
With Selection
.PasteSpecial (xlValues)
.PasteSpecial (xlFormats)
.PasteSpecial (xlPasteColumnWidths)
End With
ActiveSheet.Name = pname
End If
Next
wbNew.Sheets("Hoja1").Delete
Application.DisplayAlerts = True
End Sub
Since you are copying all worksheet, how about:
Copy & Paste (X)
SaveAS (O)
Sub Export()
Application.DisplayAlerts = False
On Error Resume Next
Dim NewWB As String
NewWB = Sheets("Control").Range("B42")
ActiveWorkbook.SaveAs Filename:=NewWB, FileFormat:=xlWorkbookNormal
ActiveWorkbook.Sheets("Control").Delete
End Sub
I had a worksheet "Control" handling all variant, you may change it yourself
On the other hand, if you really wish to use COPY & PASTE, you could use ARRAY
Workbooks.Add
ActiveWorkbook.SaveAs Filename:=FolderPath & ExcelName & ".xlsx", FileFormat:=xlNormal
Workbooks(ExcelOrigin).Activate
Sheets(Array("for coversheet", "Pivot", "CCA", "FRR", "CRS", "GSA", "Inv Summary", "UploadtoJDE", "Comat")).Copy Before:=Workbooks(ExcelName).Sheets(1)
Sheets("Sheet1").Delete
Remember to Dim (FolderPath,ExcelName,ExcelOrigin) as String
As equal them to your file name & file path
[ i can't type in those here because of error ]

Copying and pasting data using VBA code

I have a button on a spreadsheet that, when pressed, should allow the user to open a file, then copy columns A-G of the spreadsheet "Data", then paste the data from those columns on the current sheet.
I have a logic error in the code; it runs, but it pastes the selection in the wrong place.
I am having trouble referencing the two workbooks.
Here is my code:
Sub Button1_Click()
Dim excel As excel.Application
Dim wb As excel.Workbook
Dim sht As excel.Worksheet
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
f.Show
Set excel = CreateObject("excel.Application")
Set wb = excel.Workbooks.Open(f.SelectedItems(1))
Set sht = wb.Worksheets("Data")
sht.Activate
sht.Columns("A:G").Select
Selection.Copy
Range("A1").Select
ActiveSheet.Paste
wb.Close
End Sub
Use the PasteSpecial method:
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).
'So from this discussion i am thinking this should be the code then.
Sub Button1_Click()
Dim excel As excel.Application
Dim wb As excel.Workbook
Dim sht As excel.Worksheet
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
f.Show
Set excel = CreateObject("excel.Application")
Set wb = excel.Workbooks.Open(f.SelectedItems(1))
Set sht = wb.Worksheets("Data")
sht.Activate
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Close
End Sub
'Let me know if this is correct or a step was missed. Thx.