我正在尝试编写一些代码,这些代码将从Excel工作簿中收集信息,然后将所有计算确定为单独的工作簿。这包括创建列,生成值以及在用户单击我已创建的按钮后创建图表。如果信息与计算在同一工作簿(和工作表)中,我已经可以执行这些操作。我还可以在另一个工作簿中选择特定工作表。问题是,如何将这两部分代码组合起来?
以下是打开第二个工作簿的代码:
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
作为测试,我将在test_info工作簿中创建一个3乘3的数字块(1 - 9),然后对它们执行随机计算(例如减法和乘法),并在test_calculation中输出答案。 / p>
谢谢,
杰西
答案 0 :(得分:1)
这是一个基于你的代码的子代码,带有几个mod来演示wb和工作表,添加数据和图表
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
答案 1 :(得分:0)
将以下代码添加到主工作簿(不应计算数据)中:
Private Sub Workbook_Open()
Application.Calculation = xlManual
Application.CalculateBeforeSave = False
End Sub
它将强制Excel不计算任何内容。
另一方面,确保'计算'工作簿具有自动选项,即:
Private Sub Workbook_Open()
Application.Calculation = xlCalculationAutomatic
End Sub