Copy from one worksheet to another without opening excel using vba - vba

I'm trying to copy cell values from one excel to another using VBA. What I'm trying to do is that by clicking on the script, excel (without getting opened) values should automatically get copied from one worksheet to another. While executing my script I get an error which says Type Mismatch: 'Sheets'. I've read various posts but could not find an answer to this problem. My script looks like this:
ImportData_Click
Sub ImportData_Click()
Dim objExcel2
Set objExcel2 = CreateObject("Excel.Application")
' open the source workbook and select the source sheet
objExcel2.Workbooks.Open "<path>\test1_vbs.xlsx"
' copy the source range
Sheets("Sheet1").Range("A1:B2").Copy
' select current workbook and paste the values
ThisWorkbook.Activate
Sheets("Sheet2").Range("A1:B2").PasteSpecial xlPasteValues
' close the source workbook
Windows("<path>\test1_vbs.xlsx").Activate
ActiveWorkbook.Save
ActiveWorkbook.Close
End Sub

If you are going to tranfer values only between application instances, skip the clipboard and use an array.
Option Explicit
Sub ImportData_Click()
Dim objExcel2 As Object, arr As Variant
Set objExcel2 = CreateObject("Excel.Application")
' open the source workbook and select the source sheet
With objExcel2.Workbooks.Open("c:\test\test2_vbs.xlsx")
' copy the source range to variant array
arr = .Worksheets("Sheet1").Range("A1:B2").Value
' close the source workbook
.Close savechanges:=False
End With
' select current workbook and paste the values
ThisWorkbook.Worksheets("Sheet2").Range("A1").Resize(UBound(arr, 1), UBound(arr, 2)) = arr
' close the source application instance
objExcel2.Quit
Set objExcel2 = Nothing
ActiveWorkbook.Save
ActiveWorkbook.Close
End Sub

Related

How do I copy a range from one workbook to another in excel WITHOUT having to name it in VBA?

I'm looking for assistance regarding how to write a VBA command that allows me to copy a range of cells from different workbooks onto one master sheet. Let me explain further.
Everyday I receive a new excel document from my clients named based on the date it was uploaded ie. September 18, 2018 file would be called A20180918.
Once i've received a week's worth of excel files (A20180918-A20180921), I then have to copy certain information from the original uploaded file to a master tracking sheet.
So, my hurdle is such that each time I record my actions into a macro, the code includes the file name which then creates a subscript error when it's run on the next day's file.
So here's an example below of the code I have this far:
Sub CopyRange()
CopyRange Macro
'This is the line of the code that's causing problems given it's a specified workbook name
'and when I try to open tomorrow's workbook i'll run into the subscript error.
Windows("A20180914.xls").Activate
Range("A2:B2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("Master Sheet.xlsm").Activate
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
Thank you!
Here's two solutions. One to scan an Directory for files, and the other to select files. I see they've both been suggested in the comments already. :p
Sub Test()
' If you want to scan an "unprocessed files" directory
'Call ScanDir("C:\Test\")
' If you want to select files to process
Call SelectFiles
End Sub
Private Sub ScanDir(ByVal DirPath As String)
Dim oCurFile As String
oCurFile = Dir(DirPath)
Do While oCurFile <> ""
' Add the work to the file here
' Filename: DirPath & oCurFile
oCurFile = Dir()
Loop
End Sub
Private Sub SelectFiles()
Dim oFileDialog As FileDialog
Set oFileDialog = Application.FileDialog(msoFileDialogFilePicker)
oFileDialog.AllowMultiSelect = True
If oFileDialog.Show = -1 Then
Dim oFile As Variant
For Each oFile In oFileDialog.SelectedItems
' Add the work to the file here
' Filename: oFile
Next
End If
End Sub
By the looks of it you have all the workbooks open when you run the code - there are ways to have the code open each workbook in a certain folder, or ask the user to select them.
While writing this other answers have given the code for selecting files from folders.
Each workbook in the Excel Application is held in a collection of workbooks. The good thing about collections is you can step through them without know the specifics before you get there.
The code below will print the name of each workbook you have open into the immediate window. Note - these are in the same instance of Excel. If you open Excel a second time then any workbooks in that application will be in a different collection.
You don't really need the Application but I left it in to make things a bit clearer.
Sub Test()
Dim bk As Workbook
For Each bk In Application.Workbooks
Debug.Print bk.Name
Next bk
End Sub
This is the full code - note that nothing is Selected.
Sub Test()
Dim bk As Workbook
Dim Master As Workbook
Dim LastCell As Range
Set Master = Workbooks("Master Sheet.xlsm")
For Each bk In Application.Workbooks
'Checks the middle part of the file name - should be a number.
'Better ways to check the file name are available.
If IsNumeric(Mid(bk.Name, 3, 8)) Then
'Copy date from Sheet1. It's assumed each row in
'column B is populated and figures out the last cell from there.
With bk.Worksheets("Sheet1")
Set LastCell = .Cells(.Rows.Count, 2).End(xlUp)
.Range("A1", LastCell).Copy
End With
'Pastes the results to Sheet1 in the Master workbook.
'The last cell containing data in column A is found and
'then offset by 1 row.
With Master.Worksheets("Sheet1")
.Range("A" & .Rows.Count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValues
End With
End If
Next bk
End Sub
This will do it, you just need to supply the sheet name and ranges where noted:
Sub copyRange()
'File system variables
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim myDir As String
Dim Mask As String
'Workbook variables
Dim wb As Workbook
Dim sh As Worksheet
myDir = "C:\Users\Guest\Desktop" 'Insert the path where your incoming files are stored.
Mask = "*.xl??" 'This makes it so it only looks at Excel files.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.getFolder(myDir)
For Each objFile In objFolder.Files
If LCase(objFile.Name) Like LCase(Mask) Then
Set wb = Workbooks.Open(myDir & "\" & objFile.Name, , True) 'This is set to open in read only, to avoid issues with the file already being open
'The ranges you are copying/pasting are vague, supply the sheet names and ranges below
'Get Copy range with dynamic number of rows.
With wb.Sheets("Sheet1").Range("A2:B2") '<---- Specify Sheet/Range
Set copyRange = .Resize(.End(xlDown).Row, 2)
End With
'Get next available row in paste range.
With ThisWorkbook.Sheets("Sheet1").Range("G:H") '<---- Specify Sheet/Range
Set pasteRange = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0)
End With
copyRange.Copy pasteRange
wb.Close False
End If
Next objFile
End Sub

VBA copy selection range in loop

I want to ask about loop in VBA. I have this VBA code:
Sub OpenCopyPaste()
' open the source workbook and select the source sheet
Workbooks.Open Filename:="C:\Users\Adryan Permana\Downloads\Test\part8.xlsx"
Sheets("Sheet1").Select
' copy the source range
Sheets("Sheet1").Range("C2:E2,C3:E3,C4:E4,C5:E5,C6:E6,C7:E7,C8:E8,C9:E9").Select
Selection.Copy
' select current workbook and paste the values starting at A1
Windows("report.xlsx").Activate
Sheets("Sheet1").Select
Sheets("Sheet1").Range("C3").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWorkbook.Save
End Sub
I want to select all data in range "C2:E2" to "C9:E9" and paste it to other workbook.
In my current code, I need to type one by one range from C2 - C9.
I want to select data from C2-C9 in loop.
Is there any way to do it in loop?
You can copy the entire range with Range("C2:E9").Copy.
Also, there is no need to use Select, Activate and Selection, it slows down the code run-time, just use fully qulifed Wroksheets and Range instead.
Code
Option Explicit
Sub OpenCopyPaste()
Dim wb As Workbook
Dim Reportwb As Workbook
' set report workbook to workbook object (works only is the file is already open)
Set Reportwb = Workbooks("report.xlsx")
' open the source workbook and select the source sheet
Set wb = Workbooks.Open(Filename:="C:\Users\Adryan Permana\Downloads\Test\part8.xlsx")
' copy the source range and paste in 1 line , paste at "C3"
wb.Sheets("Sheet1").Range("C2:E9").Copy Destination:=Reportwb.Sheets("Sheet1").Range("C3")
Application.CutCopyMode = False
Reportwb.Save
End Sub
Instead use C2:E9
Sub OpenCopyPaste()
' open the source workbook and select the source sheet
Workbooks.Open Filename:="C:\Users\Adryan Permana\Downloads\Test\part8.xlsx"
Sheets("Sheet1").Select
' copy the source range
Sheets("Sheet1").Range("C2:E9").Select
Selection.Copy
' select current workbook and paste the values starting at A1
Windows("report.xlsx").Activate
Sheets("Sheet1").Select
Sheets("Sheet1").Range("C3").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWorkbook.Save
End Sub

Excel Macro: Setting a variable for a workbooks location?

I need to write a macro script that will copy data from one xml workbook and paste the values to another workbook. I've written the below macro that works fine, but i need to run this every week for several different documents so it means i have to replace the document name for each run.
Here's what i have so far:
Sub copying()
''''''Section 1''''''
Workbooks("Results_2561").Activate 'workbook i'm copying from
Range("B27:B41").Select
Selection.Copy
Workbooks("Overall_Results").Activate 'workbook i'm pasting to
Range("G2").PasteSpecial
''''''Section 2''''''
Workbooks("Results_2561").Activate
Range("C27:C41").Select
Selection.Copy
Workbooks("Overall_Results").Activate
Range("C2").PasteSpecial
''''''Section 3''''''
Workbooks("Results_2561").Activate
Range("I28:I40").Select
Selection.Copy
Workbooks("Overall_Results").Activate
Range("G17").PasteSpecial
''''''Section 4''''''
Workbooks("Results_2561").Activate
Range("J28:J40").Select
Selection.Copy
Workbooks("Overall_Results").Activate
Range("C17").PasteSpecial
End Sub
...
and that's only half the script. Is there a way i can declare a variable at the start and set it as the Workbooks file path so i can call that instead of typing and retyping it over and over again?
Preferably without using something like
Dim book1 as Workbook
Set book1 = Workbooks.Open("C://Results_2561.xlsm")
..as this keeps opening and closing the document when i run the script.
Thanks
since you're only interested in copying values you could use this helper Sub
Sub CopyValues(rngToCopyFrom As Range, rngToCopyTo As Range)
With rngToCopyFrom
rngToCopyTo.Resize(.Rows.COUNT, .Columns.COUNT).Value = .Value
End With
End Sub
to be exploited in your main code like follows:
Sub main()
Dim wsTo As Worksheet
Set wsTo = Workbooks("Overall_Results").ActiveSheet '<--| set the worksheet to paste values to
With Workbooks("Results_2561").ActiveSheet '<--| reference the worksheet to copy values from
CopyValues .Range("B27:B41"), wsTo.Range("G2")
CopyValues .Range("C27:C41"), wsTo.Range("C2")
CopyValues .Range("I28:I40"), wsTo.Range("G17")
CopyValues .Range("J28:J40"), wsTo.Range("C17")
End With
End Sub
should your relevant workbooks have more than one sheet, then just substitute
ActiveSheet
with
Worksheets("myRelevantShetName") '<--|change "myRelevantShetName" to the actual name of the relevant worksheet in each workbook
First of all, you don't have to Activate workbook every time when you want to copy/paste something. Just declare it in Range() property, for example:
''''''Section 1''''''
Workbooks("Results_2561").Sheets(1).Range("B27:B41").Copy
Workbooks("Overall_Results").Sheets(1).Range("G2").PasteSpecial
You can set Workbook as variable like:
Sub copying()
Dim wb1 As Workbook, wb2 As Workbook
Set wb1 = Workbooks("Results_2561")
Set wb2 = Workbooks("Overall_Results")
''''''Section 1''''''
wb1.Sheets(1).Range("B27:B41").Copy
wb2.Sheets(1).Range("G2").PasteSpecial
End Sub
Finally, as #A.S.H suggested, you can add a file dialog where you point which files you want to use. I have put it in some function (don't forget to put it in the same project as your copying macro):
Function strPath() As String
Dim intResult As Integer
Application.FileDialog(msoFileDialogFilePicker).Title = "Select file"
intResult = Application.FileDialog(msoFileDialogFilePicker).Show
If intResult <> 0 Then
strPath = Application.FileDialog(msoFileDialogFilePicker).SelectedItems(1)
End If
End Function
So your final code for Section 1 would look like:
Sub copying()
Dim wb1 As Workbook, wb2 As Workbook
MsgBox "Show file to copy form."
Set wb1 = Workbooks.Open(strPath())
MsgBox "Show file to paste in."
Set wb2 = Workbooks.Open(strPath())
''''''Section 1''''''
wb1.Sheets(1).Range("B27:B41").Copy
wb2.Sheets(1).Range("G2").PasteSpecial
End Sub

Paste Values into new worksheet for all Open Worksheets including pictures

I am trying to create a renamed copy of all active workbooks (even non macro-enabled ones) without formulas, possibly by pasting values but without modifying images. I am working with Excel 2007.
My process would ideally be to:
1) Create a do while there are xls files loop that converts all xls files to xlsm. One possible addition would be an array to store A)the worksheet name(s) B)Its tabs name and their status
2) Run a for each or for loop that automatically pastes values for all active worksheets include those with graphs or other images into a new document that has the same name with all small addition at the end.
3) Convert my newly-named files containing values only into xls.
One issue I am running into when I try to do this has to do with links. The initial worksheets have formulas with links that do not automatically update. When I do this, the formulas in the original worksheet with link references tend to get corrupted.
Here is a general macro I found for pasting values:
Sub test()
Dim MyNames As Range, MyNewSheet As Range
Set MyNames = Range("R5").CurrentRegion ' load contigeous range into variable
For Each MyNewSheet In MyNames.Cells ' loop through cell children of range variable
Sheets.Add.Name = MyNewSheet.Value
Next MyNewSheet
MyNames.Worksheet.Select ' move selection to original sheet
End Sub
I think this is what you're asking for:
Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim counter As Integer
Dim filePath As String
Set wb = ActiveWorkbook
countet = 1
filePath = "c:/" 'Enter your destination folder here
For Each ws In wb.Sheets
Sheets("Sheet1").Copy
With ActiveSheet.UsedRange
.Value = .Value
End With
ActiveWorkbook.SaveAs filePath & counter & ".xlsx", FileFormat:=51
counter = counter + 1
Next ws
End Sub
This is mostly taken from here.
The counter is a bit of a hack to make sure that the files aren't all being saved as the same name and overwriting each other. Maybe there's a more appropriate way that you can get around this.

VBA - Changing Copying from a Directory to copying from a server

Apreciate any help and excuse me if my terminology is incorrect.
This is a basic macro that opens a file from loacation A and copies the specified content,
It then pastes the content into the current Workbooks, specified worksheet and cell, that has run this macro.
My question is around the "FileName.csv". This is currently scheduled to be dumped in Location A "V:\Dir1\SubDir1\" periodically.
How would I go about Retrieving this file, "FileName.csv", if I started scheduling it to be dumped in loacation B "http://172.1.2.3/Dir1/SubDir1/FileName.csv" a server of some sort?
I would obviusly just like to edit the existing macro to allow for this change.
Sub CopyCSVFile1()
'workbook to copy from
WBToCopy = "FileName.csv"
'workbook path to copy from
WBpthToCopy = "V:\Dir1\SubDir1\"
'workbook to paste to
'WBToPasteTo = "ResourcesV1.xlsm" not needed here as pasting to active workbook
'workbook sheet to paste to
WBSheetToPasteTo = "Raw1"
''workbook path to paste to
'WBPthToPasteTo = "N:\Engineering\Network Performance\Capacity\SG_GG\SGSN Resources\" ' not needed here as pasting to active workbook
'range to select to copy
RangeToSelectToCopy = "A3:B149"
'cell to paste to
CellToPasteTo = "A3" ' need to work this out before assignment
Dim Merged As Object
Dim Data As Object
Set Data = ActiveWorkbook
'debug.print "ActiveWorkbook.Path = " & ActiveWorkbook.Path
Debug.Print "ActiveWorkbook.Path = " & Data.Path
Sheets(WBSheetToPasteTo).Select ' this is the sheet where you want to paste to
Workbooks.Open Filename:=WBpthToCopy & WBToCopy, local:=True
Set Merged = ActiveWorkbook ' this assigns the current active workbook to merged whish is the one I want to copy from
Range(RangeToSelectToCopy).Select ' this value just for this example should be A4 normally
Selection.Copy
Data.Activate ' this activates the Data workbook which happens to be the workbook where this macro resides
Range(CellToPasteTo).Select ' select where I want to past my data
ActiveSheet.Paste ' paste the data
Application.DisplayAlerts = False
Merged.Close 'SaveChanges = False
Application.DisplayAlerts = True
End Sub
This worked for me:
Sub CopyCSVFile1()
Dim wb As WorkBook, WBToCopy As String, WBpthToCopy As String
'workbook to copy from
WBToCopy = "test.csv"
'workbook path to copy from
WBpthToCopy = "http://127.0.0.1/testpages/"
'open the source workbook
Set wb = Workbooks.Open(WBpthToCopy & WBToCopy)
'...
'do something with wb...
'...
wb.Close False
End Sub