• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Macro Basic information needed

Hi Guys,


I am very much new to VBA and was trying hands on various copy paste methods.I wnated to know basic code that world copy and paste the values in a worksheet from another worksheet when BOTH ARE CLOSED.I managed to write a code when both the worksheets are open.I wanted to write when they are closed.Any help would be appreciated.


Code for Opened workbooks


"


Sub test()


workbooks("Test1.xlsx").sheets("sheet1").range("A1:B5").copy _

workbooks("Test2.xlsx").sheets("sheet2").range (A1:B5")


Thanks and Regards

Vaibhav
 
You'll have to open at least the destination workbook. Using the code from here:

http://www.rondebruin.nl/copy7.htm

your macro could look like this. Note that you'll need to change the file paths to match your need. Current code does not save or close Test2.xlsx, but you could easily add that to the end of the MainMacro.

[pre]
Code:
Sub MainMacro()
Dim SourceBook As String
Dim SourcePath As String
Dim SourceSheet As String
Dim SourceRange As String
Dim DestRange As Range

Application.ScreenUpdating = False
Workbooks.Open FileName:="C:My DocumentsTest2.xlsx"
Set DestRange = ActiveWorkbook.Worksheets("sheet2").Range("A1:B5")

SourceBook = "Test1.xlsx"
SourcePath = "C:My Documents"
SourceSheet = "sheet1"
SourceRange = "A1:A5"

On Error Resume Next
Call GetRange(SourcePath, SourceBook, SourceSheet, SourceRange, DestRange)
On Error GoTo 0
Application.ScreenUpdating = True

End Sub

Sub GetRange(FilePath As String, FileName As String, SheetName As String, _
SourceRange As String, DestRange As Range)

Dim Start

'Go to the destination range
Application.Goto DestRange

'Resize the DestRange to the same size as the SourceRange
Set DestRange = DestRange.Resize(Range(SourceRange).Rows.Count, _
Range(SourceRange).Columns.Count)

'Add formula links to the closed file
With DestRange
.FormulaArray = "='" & FilePath & "[" & FileName & "]" & SheetName _
& "'!" & SourceRange

'Wait
Start = Timer
Do While Timer < Start + 2
DoEvents
Loop

'Make values from the formulas
.Copy
.PasteSpecial xlPasteValues
.Cells(1).Select
Application.CutCopyMode = False
End With
End Sub
[/pre]
 
Back
Top