2017-04-10 84 views
0

我已經搜索過此問題,但所有示例都太複雜。 我只是不能使用「設置工作簿」和「設置工作表」對象。我將得到錯誤1004:對象定義的錯誤。正確指定工作簿和工作表VBA

我想從目標文件片 「路徑」 讀取路徑:C:\用戶\霍爾格\文件\ VBA \ WB_data.xlsx

請人幫忙。

Sub Get_numbers() 

'I have got 2 sheets 
Dim WB_dest As Workbook 
Dim WB_data As Workbook 

'I need 3 worksheets 
Dim path_sheet As Worksheet 
Dim dest_sheet As Worksheet 
Dim data_sheet As Worksheet 

'Data worksheet's path 
Dim path As String 

'Counter 
Dim i As Byte 

'I run this sub from destination file sheet "PATH" which is already open 
Set WB_dest = ThisWorkbook 
Set path_sheet = WB_dest.Worksheets("Path") 
Set dest_sheet = WB_dest.Worksheets("TO") 

'I set worksheet from the Excel taht I do not need to open, just reading 
Set WB_data = Workbooks.Open(path) 
Set data_sheet = WB_data.Worksheets("FROM") 

'Data sheet contains three numbers in the first column 
'and destination sheet also contains only three numbers in the first coulm 
'I would like to add data_sheet numbers after dest_sheet numbers 
For i = 4 To 6 
    dest_sheet.Cells(i, 1) = data_sheet(i, 1) 
Next i 
+0

當您嘗試打開工作簿你從來沒有定義變量'path'所以,它不能找到null' – tigeravatar

+0

的'路徑是什麼' data_sheet(i,1)'應該是? 'data_sheet'是一個工作表。 '(i,1)'應該是指什麼? – BruceWayne

回答

0

嘗試......

Sub Get_numbers() 

'I have got 2 sheets 
Dim WB_dest As Workbook 
Dim WB_data As Workbook 

'I need 3 worksheets 
Dim path_sheet As Worksheet 
Dim dest_sheet As Worksheet 
Dim data_sheet As Worksheet 

'Data worksheet's path 
Dim path As String 

'Counter 
Dim i As Byte 

path = "C:\Users\Holger\Documents\VBA\WB_data.xlsx" 

'I run this sub from destination file sheet "PATH" which is already open 
Set WB_dest = ThisWorkbook 
Set path_sheet = WB_dest.Worksheets("Path") 
Set dest_sheet = WB_dest.Worksheets("TO") 

'I set worksheet from the Excel taht I do not need to open, just reading 
Set WB_data = Workbooks.Open(path) 
Set data_sheet = WB_data.Worksheets("FROM") 

'Data sheet contains three numbers in the first column 
'and destination sheet also contains only three numbers in the first coulm 
'I would like to add data_sheet numbers after dest_sheet numbers 

data_sheet.Range("A4:A6").Copy 
dest_sheet.Range("A4").PasteSpecial xlPasteValues 
'For i = 4 To 6 
' dest_sheet.Cells(i, 1) = data_sheet(i, 1) 
'Next i 

End Sub 
相關問題