Copying from closed workbook - vba

I have been searching for over a hour now and can not find anything that works for this and would appreciate any help at all. I have been using the following code:
Sub copySheet()
Dim srcBook As Workbook
Set srcBook = Application.Workbooks.Open(ThisWorkbook.Path & "\Book1.xlsx")
srcBook.Sheets("Sheet1").Copy After:=ThisWorkbook.Sheets(1)
srcBook.Close False
End Sub
This copies as expected however, in the copied workbook it creates a new sheet "Sheet1(2)" instead of adding this to the existing sheet1. If repeated it creates "Sheet1(3)", "Sheet1(4)", "Sheet1(5)", etc...
I am really stuck with this and cannot find an answer anywhere.

There are two possible tasks at issue here:
Copying a sheet, which your code does successfully
Copying the contents of a sheet, which is also called a Range
It sounds like what you actually want to do is copy a Range to an existing worksheet. Try this instead:
Sub copySheetContents()
Dim srcBook As Workbook
Set srcBook = Application.Workbooks.Open(ThisWorkbook.Path & "\Book1.xlsx")
srcBook.Sheets("Sheet1").UsedRange.Copy
ThisWorkbook.Sheets(1).Cells(1, 1).PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
srcBook.Close False
End Sub
Note that the above assumes that your used range in the source workbook starts at cell A1.

If you are trying to just overwrite what is in your current sheet1:
Sub copySheet()
Dim srcBook As Workbook
Set srcBook = Application.Workbooks.Open(ThisWorkbook.Path & "\Book1.xlsx")
srcBook.Sheets("Sheet1").UsedRange.Copy Destination:=ThisWorkbook.Sheets("Sheet1").Cells(1,1)
srcBook.Close False
End Sub

Related

VBA Troubles with removing .select from code

I have been trying to remove the .Select from my code because I found out recently it's not really an efficient way to do things, but i can't get this piece of code to work.
The data I am pasting comes from another program so it is on the clipboard
My current code(which works):
Range("A3:A3").Select
ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
False
I have been trying to fix it in two ways, but both give errors.
Option 1:
Worksheets("Orders").Range("A3").PasteSpecial _
Format:="Text", Link:=False, DisplayasIcon:=False
Option 2:
Dim ws As Worksheet
Set ps = Sheets("Orders")
With ps.Range("A3")
.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
False
End With
Both give "application defined or object defined error" so I'm doing something wrong, i just can't figure out where the wrong part is.
Try like this
Dim Ws As Worksheet
Set Ws = Sheets("Orders")
Ws.Range("A3").PasteSpecial xlPasteAll
Updated based on comments
As you are pasting from the clipboard directly, not from another range, you will need the Worksheet.PasteSpecial version, rather than Range.PasteSpecial.
Sub PasteFromClipboard()
'
'code which loads clipboard
'
With Worksheets("Orders")
.Activate 'activate the worksheet so that you can select a range on this sheet
.Range("A3").Select
.PasteSpecial Format:="Text", Link:=False, DisplayasIcon:=False
End With
End Sub
For the first option you forgot the ""
This should work:
Worksheets("Orders").Range("A3").PasteSpecial _
Format:="Text", Link:=False, DisplayasIcon:=False
For the second option change ps in ws as JC Guidicelli said.
try to declare your workbook :
Dim wb As Workbook
Set wb = ThisWorkbook
and after your worksheet :
Dim ws As Worksheet
Set ws = wb.Sheets("Orders")
and past :
ws.Range("a3").PasteSpecial xlValues

Copying Data from a worksheet to another workbook

How to Copy data from one excel file to another file in different folder using VBA?
From the above link I got the codes that I was looking for.
My Query hasn't been solved yet.
I made few changes to the code to my requirements and still I get wrong results.
Below mentioned is the code that I used.
Sub TransferDataV2() 'transfer stuff from this workbook to workbook 2
Dim strPath2 As String
Dim wbkWorkbook1 As Workbook
Dim wbkWorkbook2 As Workbook
'define paths and filenames
strPath2 = "E:\Purchase Register 2015-16.xlsx"
'open files
Set wbkWorkbook1 = ThisWorkbook '### changed this
Set wbkWorkbook2 = Workbooks.Open(strPath2)
'copy the values across
'### change the sheet and range to what you need
wbkWorkbook1.Activate
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
wbkWorkbook2.Worksheets("Sheet1").Activate
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveCell.Offset(1).Select
ActiveCell.PasteSpecial
'close the workbook
wbkWorkbook2.Close (True)
End Sub
Now whenever I update some data in this workbook and try to save to another workbook, the copied data replaces the already available data in the strPath2 = "C:\put in this.xlsx".
The result I require is the copied data must be saved in the put in this.xlsx
but at the end of the table. Instead This code copies the data and saves them in from A2:G5. Kinldy Advice
After Selection.Copy try:
wbkWorkbook2.Worksheets("Sheet1").Cells(wbkWorkbook2.Worksheets("Sheet1").UsedRange.Row + 1, 1).PasteSpecial
'close the workbook
wbkWorkbook2.Close (True)

Simple Excel VBA macro failing

I have the following simple macro to copy data from a closed worksheet. The code runs fine from the VBA editor but fails with a subscript error when run from Excel via macro. The paste special statement appears to be the issue.
I just can't see where the problem is, can anyone help?
Dim wsMaster As Worksheet
Set wsMaster = Worksheets("Master Data")
Dim lastrow As Long
Dim Files As String
Files = "Download.xlsx"
Dim filepath As String
filepath = "C:\users\ms612533\desktop\"
Application.ScreenUpdating = False
wsMaster.Activate
Cells.Select
Selection.Clear
Workbooks.Open (filepath & Files)
lastrow = Worksheets("Global").UsedRange.Rows.Count
Worksheets("Global").Range("A1:V" & lastrow).Copy _
wsMaster.Range("B1")
Worksheets("Global").Range("CV1:cv" & lastrow).Copy
wsMaster.Range("a1").PasteSpecial (xlValues)**
Application.CutCopyMode = False
ThisWorkbook.Activate
Call CloseAll
Application.ScreenUpdating = True
End Sub
Sub CloseAll()
' Close all but the active workbook
Dim wkbk As Workbook
Application.ScreenUpdating = False
For Each wkbk In Application.Workbooks
If wkbk.Name <> ActiveWorkbook.Name Then
wkbk.Close SaveChanges:=False
End If
Next
Application.ScreenUpdating = True
End Sub
I think there's something wrong with the PasteSpecial line: when I use the macro recorder, I get something like this:
wsMaster.Range("a1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
I think we can ignore the parameters after the first. Then we have this:
wsMaster.Range("a1").PasteSpecial Paste:=xlPasteValues
Note that there are no parens (()) around the arguments: PasteSpecial doesn't return anything so it should be treated like a function. That's probably where the subscript issue is coming from.
Also notice the parameter, which comes from the xlPasteType enum, is a little different from the value you had.
The code appears to work fine when calling the macro from a button, but it doesn't work from a shortcut. I'll put it down to an Excel 'feature' and move on.

How can I disable the clipboard prompt in excel vba when I close the workbook?

So I'm working with multiple workbooks from which I copy all the data from Sheet1 from each one into their respective sheet on the master workbook. After I do that, I have the multiple workbooks encoded to close. However, an annoying prompt asking if I want to keep the copied data on clipboard consistently pops up and I want to either have it not pop up or when it does, I want "No" to be automatically chosen.
I know there's a similar question that's been asked but it hasn't worked for me and I'm thinking it's because I have a rectangular area of data instead of just a column? I really new at vba but I tried messing around with the code in Disable clipboard prompt in Excel VBA on workbook close but I've had no luck.
Here's my original code:
Sub CFM56copydata()
Dim wbk As Workbook
'The workbook is opened using the text from a textbox in a userform i.e:
strFirstFile = Userform1.dog.Text
Set wbk = Workbooks.Open(strFirstFile)
With wbk.Sheets("Sheet1")
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
End With
Set wbk2 = ThisWorkbook
wbk2.Sheets("dog").Range("A1").Insert
wbk.Close
End Sub
and here's how I tried to tweak it so I avoided using the clipbaord at all. (Didn't work, gives me a debug error on line 12)
Sub fix()
Dim wbk As Workbook
strFirstFile = Userform1.CFM56path.Text
Set wbk = Workbooks.Open(strFirstFile)
Set wbk2 = ThisWorkbook
Dim rSrc As Range
Dim rDst As Range
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Set rSrc = Selection
Set rDst = wbk2.Sheets("dog").Cells("A1").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
rDst = rSrc
wbk.Close
End Sub
If the clipboard prompt is the problem, just empty it after your done pasting.
wbk2.Sheets("dog").Range("A1").Insert
Application.CutCopyMode = False
wbk.Close
It should work if you change your wbk.Close statement to:
Application.DisplayAlerts = False
wbk.Close
Application.DisplayAlerts = True

Save values (not formulae) from a sheet to a new workbook?

I am using the following function to save a worksheet from a workbook and save it to a separate workbook. However, it is saving the formulas, whereas I would rather just the values end up in the final workbook. How can I modify this so the resultant workbook doesn't contain formulae and just values?
Sub Sheet_SaveAs(FilePath As String, SheetToSave As Worksheet)
Dim wb As Workbook
Set wb = Workbooks.Add(xlWBATWorksheet)
With wb
SheetToSave.Copy After:=.Worksheets(.Worksheets.Count)
Application.DisplayAlerts = False
.Worksheets(1).Delete
Application.DisplayAlerts = True
.SaveAs FilePath
.Close False
End With
End Sub
Using the link kindly provided I tried this, but to no avail:
Sub Sheet_SaveAs(FilePath As String, SheetToSave As Worksheet)
Dim wb As Workbook
Set wb = Workbooks.Add(xlWBATWorksheet)
With wb
SheetToSave.Copy After:=.Worksheets(.Worksheets.Count)
Application.DisplayAlerts = False
.Worksheets(1).Delete
.Worksheets(1).Copy
.Worksheets(1).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.DisplayAlerts = True
.SaveAs FilePath
.Close False
End With
End Sub
but I get an error on the pastespecial line??
.Worksheets(1).Copy
This copies the sheet itself and does not relate to PasteSpecial. You could use:
.Worksheets(1).UsedRange.Copy
or similar. For example, Worksheets(1).Cells.Copy.
I assume it should be Worksheets(.Worksheets.Count) though.
In the following I am using SpecialCells to identify only the formulas in the worksheet, and setting rng.Value = rng.Value to convert these to the results of the formulas.
Sub Sheet_SaveAs(FilePath As String, SheetToSave As Worksheet)
Dim wb As Workbook
Dim ws As Worksheet
Dim rngFormulas As Range, rng As Range
Set wb = Workbooks.Add(xlWBATWorksheet)
With wb
SheetToSave.Copy After:=.Worksheets(.Worksheets.Count)
Set ws = .Worksheets(.Worksheets.Count)
Application.DisplayAlerts = False
.Worksheets(1).Delete
Application.DisplayAlerts = True
With ws
Set rngFormulas = ws.Cells.SpecialCells(xlCellTypeFormulas)
For Each rng In rngFormulas
rng.Value = rng.Value
Next rng
End With
.SaveAs FilePath
.Close False
End With
End Sub
You will need to add some error handling code, to handle the case where there are no formulas in the copied worksheet. (Array formulas may also need to be accounted for.)
The easiest way to copy the values is to do it in 2 steps:
Copy the sheet, then replace the formulas with their values
After:
.Worksheets(1).Delete
in your original code, add the lines:
With Range(Worksheets(.Worksheets.Count).UsedRange.Address)
.Value = .Value
End With
The .value=.value is telling excel to replace every value with the value that is currently being displayed, so all formulas will be replaced with their calculated value
Sorry, answer was starting to look a complete mess, so deleted it and started again. I've written this - it appears to work fine when I tested it - you just need an extra line to save any resulting spreadsheet. :)
For Each Cell In ActiveSheet.UsedRange.Cells
Cell.Copy
Cell.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Next