【问题标题】:Assigning workbook and worksheet properly VBA正确分配工作簿和工作表 VBA
【发布时间】:2017-04-11 00:14:50
【问题描述】:

我已经搜索过这个问题,但是所有的例子都太复杂了。 我只是不能使用“设置工作簿”和“设置工作表”对象。我会收到错误 1004:对象定义的错误。

我想从目标文件表“路径”中读取路径:C:\Users\Holger\Documents\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

【问题讨论】:

  • 您从不定义变量path,所以当您尝试打开工作簿时,找不到null 的路径
  • data_sheet(i, 1) 应该是什么? data_sheet 是一个工作表。 (i,1) 应该引用什么?

标签: vba excel worksheet


【解决方案1】:

试试这个...

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

【讨论】:

    猜你喜欢
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多