2011-02-22 118 views
0

我正在嘗試編寫一些代碼,這些代碼將從Excel工作簿收集信息,然後確定所有計算到單獨的工作簿中。這包括創建列,生成值以及在用戶單擊我已經創建的按鈕後創建圖形。如果信息與計算在同一工作簿(和工作表)中,則我可以執行這些操作。我也能夠在另一個工作簿中選擇特定工作表。問題是,如何將這兩個代碼組合起來工作?Excel VBA使用單獨的工作簿執行計算

下面是打開一個第二個工作簿的代碼:

Dim file_path As String 
Dim excel_title As String 
Dim second_excel_title As String 

file_path = "C:\Work\EXCEL_TEST\" 
excel_title = "test_info" 
second_excel_title = "test_calculation" 

Set wbs = Workbooks 
wbs.Open (file_path & excel_title) 
Set wb = wbs.Item(excel_title) 
wb.Sheets.Add after:=wb.Sheets(wb.Sheets.Count) 

wb.Sheets("Sheet1").Select 

作爲測試我要作出3由3個數字的塊(1 - 9)在test_info工作簿,然後執行隨機計算(例如減法和乘法)並在test_calculation中輸出答案。

謝謝

傑西

回答

1

下面是根據你的代碼有幾個MODS的演示指世行和牀單子,加入數據和圖表

Sub zx() 
    Dim file_path As String 
    Dim excel_title As String 
    Dim second_excel_title As String 
    Dim wb As Workbook 
    Dim sh1excel As Worksheet, sh2excel As Worksheet 
    Dim cht1 As Chart, cht2 As Chart 
    Dim i As Long, j As Long 

    Set sh1excel = ThisWorkbook.ActiveSheet 
    file_path = "C:\Users\Chris\Documents\" 
    excel_title = "test_info" 
    second_excel_title = "test_calculation" 

    Set wb = Workbooks.Open(file_path & excel_title) 

    Set sh2excel = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count)) 
    wb.Activate 
    sh2excel.Activate 

    ' Put some data in test_info at C3:D5 
    For i = 0 To 2 
    For j = 0 To 2 
     sh2excel.Cells(i + 3, j + 3) = i * 3 + j + 1 
    Next j, i 

    ' Calculate from test_info into second_excel_title 
    For i = 0 To 2 
    For j = 0 To 2 
     sh1excel.Cells(i + 3, j + 3) = sh2excel.Cells(i + 3, j + 3)^2 
    Next j, i 

    ' or put it as a formula 
    For i = 0 To 2 
    For j = 0 To 2 
     sh1excel.Cells(i + 3, j + 3) = "=[" & wb.Name & "]" & sh2excel.Name & "!" & sh2excel.Cells(i + 3, j + 3).Address & "^2" 
    Next j, i 

    ThisWorkbook.Activate 
    'Add a chart into second_excel_title 
    Set cht1 = ThisWorkbook.Charts.Add 
    cht1.Activate 
    cht1.Name = "DatafromThisBook" 
    Do While cht1.SeriesCollection.Count > 0 
     cht1.SeriesCollection.Item(1).Delete 
    Loop 
    cht1.SetSourceData Source:=sh1excel.Range("C3:E5") 

    Set cht2 = ThisWorkbook.Charts.Add 
    cht2.Activate 
    cht2.Name = "DatafromOtherBook" 
    Do While cht2.SeriesCollection.Count > 0 
     cht2.SeriesCollection(1).Delete 
    Loop 
    cht2.SetSourceData Source:=sh2excel.Range("C3:E5") 


End Sub 
+0

我實際上最終誤解了我的老闆想要的東西,但這對我仍然有很大的幫助。非常感謝你 – 2011-02-23 21:41:08

0

添加到主簿(即不應該計算數據)下面的代碼:

Private Sub Workbook_Open() 
    Application.Calculation = xlManual 
    Application.CalculateBeforeSave = False 
End Sub 

它會強制Excel不算什麼。

在另一方面,確保「計算」工作簿具有自動選項,即:

Private Sub Workbook_Open() 
    Application.Calculation = xlCalculationAutomatic 
End Sub 
相關問題