2017-02-14 359 views
0

我試圖將信息從一個工作簿複製到另一個現有工作簿,但正在添加錯誤的信息。VBA從一個工作簿複製到另一個工作簿

Sub Set_Open_ExistingWorkbook() 
Dim UserRoleWkb As Workbook, ConfigWkb As Workbook, UserRoleWkst As Worksheet, ConfigWkst As Worksheet 
Set UserRoleWkb = Workbooks.Open("C:\Users\cs\Desktop\Ar.xlsx") 
**Set ConfigWkb = ActiveWorkbook** 
Set UserRoleWkst = UserRoleWkb.Sheets("RS Users") 
**Set ConfigWkst = ActiveWorkbook.ActiveSheet** 

Dim i As Integer, j As Integer 
j = 10 'user role 
For i = 8 To 16 'config 
    If ConfigWkst.Cells(i, 2).Value <> "" Then 
     UserRoleWkst.Cells(j, 2).Value = ConfigWkst.Cells(i, 2).Value 
     j = j + 1 
    End If 
Next i 

End Sub 

帶**的代碼部分是問題。當我調用ActiveWorkbook和ActiveSheeet時,它從UserRoleWkst(工作表)中獲取信息,而不是我想要的:Configwkst。

我都試過,但將獲得的ConfigWkst行錯誤,代碼將不會運行:

Sub Set_Open_ExistingWorkbook() 
Dim UserRoleWkb As Workbook, ConfigWkb As Workbook, UserRoleWkst As Worksheet, ConfigWkst As Worksheet 
Set UserRoleWkb = Workbooks.Open("C:\Users\cs\Desktop\Ar.xlsx") 
**Set ConfigWkb = ActiveWorkbook** 
Set UserRoleWkst = UserRoleWkb.Sheets("RS Users") 
**Set ConfigWkst = ConfigWkb.Sheets("Users") 

Dim i As Integer, j As Integer 
j = 10 'user role 
For i = 8 To 16 'config 
    If ConfigWkst.Cells(i, 2).Value <> "" Then 
     UserRoleWkst.Cells(j, 2).Value = ConfigWkst.Cells(i, 2).Value 
     j = j + 1 
    End If 
Next i 

End Sub 

任何幫助表示讚賞。謝謝!

回答

1

一旦你打開另一個工作簿,然後將成爲ActiveWorkbook,所以你需要打開UserRoleWkb

Set ConfigWkb = ActiveWorkbook 
Set ConfigWkst = ConfigWkb.ActiveSheet 

Set UserRoleWkb = Workbooks.Open("C:\Users\cs\Desktop\Ar.xlsx") 
Set UserRoleWkst = UserRoleWkb.Sheets("RS Users") 
之前得到的是參考
相關問題