简体   繁体   中英

Macro To Copy And Paste From One Workbook To current workbook

I tried below macro to copy the value in excel name "3" to current excel name "1" but when i execute i get the compile error method or data member not found i am not good in Vb script any one please help me out

Sub Update()

Dim sPath As String
Dim objExcel As Application
Dim sValue As String
Dim wbTarget As Workbooks
Dim strName As String
Set wbThis = ActiveWorkbook
strName = ActiveSheet.Name
sPath = "C:\Users\nikhil.surendran\Desktop\1"
Set wbTarget = Workbooks.Open("C:\Users\nikhil.surendran\Desktop\3" & strName & ".xlsx")

sValue = wbTarget.Sheets(1).Range("A1").Value

Set objExcel = CreateObject("Excel.Application")
With objExcel
.Visible = False
.DisplayAlerts = 0
.ActiveWorkbook.Sheets(1).Range("B11").Value = sValue
.ActiveWorkbook.Save
.Quit
End With

End Sub



Thanks in Advance.

Assuming that "3.xlsx" is your file name from which you want to copy the data into the current workbook.And also from first sheet of "3.xlsx" to first sheet of current workbook.

  Sub Update()

    Dim wbkSource           As Workbook

    Set wbkSource = Workbooks.Open("C:\Users\nikhil.surendran\Desktop\3.xlsx")
    wbkSource.Worksheets(1).Range("A1").CurrentRegion.Copy ThisWorkbook.Worksheets(1).Range("A1")

  End Sub

Try this code : Assuming your code is running from current workbook. You can refer to Current Workbook as ThisWorkbook and the workbook which you are opening as wbTarget

Sub Update()

Dim sPath As String
Dim sValue As String
Dim wbTarget As Workbook
Dim strName As String

strName = ActiveSheet.Name ' Explicitly provide the sheet name
sPath = "C:\Users\nikhil.surendran\Desktop\1"
Set wbTarget = Workbooks.Open("C:\Users\nikhil.surendran\Desktop\3" & strName & ".xlsx")
sValue = wbTarget.Sheets(1).Range("A1").Value

ThisWorkbook.Sheets(1).Range("B11").Value = sValue 
ThisWorkbook.Save
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM