如何让VBA不将输出放入活动表?

时间:2015-03-16 14:04:48

标签: excel vba

我正在使用已被拉入单个工作簿的一堆csv文件。我正在一起尝试将它们整合到一个报告中。最后,我将数据放入一个数组中,然后放入一张表中。

然而,每当我运行sub时,它都会将数据加载到活动工作表中。无论我在工作簿中的哪个位置,如何将数据显示在同一工作表中?

这就是我所拥有的:

Dim starting_cell_range As Range
Set starting_cell_range = Range(find_last_column("Data_History")) 

Dim n As Integer
With Worksheets("Data_History")
    For n = 0 To 18
        starting_cell_range.Offset(n, 1) = final_array(n)
    Next n

End With

2 个答案:

答案 0 :(得分:1)

问题是您在获取工作表之前设置了范围:

Set starting_cell_range = Range(find_last_column("Data_History")) 'this is using the active sheet

Dim n As Integer
With Worksheets("Data_History") 'this is the sheet you want

因此,只需在设置工作表后移动设置范围的行。请记住使用.Range代替Range,因为您位于with区块中(就像调用Worksheets("Data_History").Range(...)

一样

以下是完整代码:

Dim starting_cell_range As Range

Dim n As Integer
With Worksheets("Data_History")
    Set starting_cell_range = .Range(find_last_column("Data_History"))
    For n = 0 To 18
        starting_cell_range.Offset(n, 1) = final_array(n)
    Next n

End With

答案 1 :(得分:0)

问题在于,当您定义范围时,它会在活动表中自动定义。将其置于With块中,不会更改范围的定义。试试这个:

Dim CurrWB As Workbook
Dim WSToCopyTo As Worksheet
Dim starting_cell_range As Range
Set CurrWB = ActiveWorkbook
Set WSToCopyTo = CurrWB.Sheets("Data_History") 
Set starting_cell_range = WSToCopyTo.Range(find_last_column("Data_History")) 

Dim n As Integer
For n = 0 To 18
    starting_cell_range.Offset(n, 1) = final_array(n)
Next n

With块没有做任何事情,所以我把它拿出来了。