简体   繁体   中英

Assigning workbook and worksheet properly VBA

I have searched for this issue already, but all the examples are way too complicated. I just cannot use "Set workbook" and "Set worksheets" object. I will get error 1004: Object-defined error.

I would like to read path from the destination file sheet "Path": C:\\Users\\Holger\\Documents\\VBA\\WB_data.xlsx

Please someone help.

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

Try this...

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

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