2013-05-09 160 views
1

我嘗試下面的宏將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\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. 

回答

0

試試此代碼:假設您的代碼正在從當前工作簿運行。您可以參考當前工作簿作爲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\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 
+0

謝謝Santhosh它工作正常。 – 2013-05-09 11:49:00

+0

@NikhilSurendran歡迎:) – Santosh 2013-05-09 11:57:27

2

假設「3.xlsx」是你的文件名,從中您希望將數據複製到當前workbook.And也從第一張「3.xlsx」到第一張當前工作簿。

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 
+0

任何使用CurrentRegion的理由? – Santosh 2013-05-09 11:31:01

+0

只是爲了複製sheeet中的所有非連續數據,因爲沒有給出後數據描述....如果數據不連續,則可以使用usedrange。我沒有使用UsedRange,因爲使用UsedRange有一些缺點。 – Transformer 2013-05-10 03:41:18

相關問題