vba 从一个工作簿复制和粘贴到当前工作簿的宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16460000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:02:43  来源:igfitidea点击:

Macro To Copy And Paste From One Workbook To current workbook

excelexcel-vbavba

提问by Nikhil Surendran

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

我尝试在下面的宏中将 excel 名称“3”中的值复制到当前的 excel 名称“1”,但是当我执行时,我得到了编译错误方法或未找到数据成员我在 Vb 脚本中不擅长任何人请帮助我

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"
Set wbTarget = Workbooks.Open("C:\Users\nikhil.surendran\Desktop" & 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.

采纳答案by Santosh

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

试试这个代码:假设您的代码是从当前工作簿运行的。您可以将当前工作簿称为ThisWorkbook以及您正在打开的工作簿作为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"
Set wbTarget = Workbooks.Open("C:\Users\nikhil.surendran\Desktop" & strName & ".xlsx")
sValue = wbTarget.Sheets(1).Range("A1").Value

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

回答by Transformer

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.

假设“3.xlsx”是您要将数据复制到当前工作簿中的文件名。并且还从“3.xlsx”的第一张纸到当前工作簿的第一张纸。

  Sub Update()

    Dim wbkSource           As Workbook

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

  End Sub