簡體   English   中英

如何防止VBA將輸出放入活動表?

[英]How do I keep VBA from putting output into the active sheet?

我正在處理一堆已拉入單個工作簿的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

問題是您要在獲取工作表之前設置范圍:

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

問題在於,當您定義范圍時,它會在活動表中自動定義。 將其放在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塊沒有執行任何操作,因此我將其取出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM