Excel 宏练习
任务描述:
利用 Excel 绘制函数图像 f(x)=x^2/3+0.9*(3.3-x^2)^1/2*sin(a*x),并通过按钮事件来刷新图像。
问题分析:
可以参考类似 Matlab 绘图的方式,定义自变量 x:[-1.816, 1.816, 0.1](即根号 3.3),因变量 y:= POWER(A1*A1,1/3)+0.9*POWER((3.3-A1*A1),1/2)*SIN($C$1*A1)(其中 a 的值存放在 $C$1 单元格中)然后插入关于 y 的折线图;
按钮事件可以通过插入矩形,并为其定义宏(快捷键:Alt+F11)来更新单元格 $C$1 的值。
用 ExcelVBA 来实现:
1、初始化基础数据
Sub InitData() '创建自变量 x 并赋值 Dim xStart As Single xStart = 1.816 Dim N As Integer N = 1000 Dim i As Integer For i = 1 To N + 1 Cells(i, 1) = (-1) * xStart + (i - 1) / 1000 * (xStart * 2) Next i = i + 1 '创建折线图(通过录制宏来获取脚本) Dim strN As String strN = "B1:B" & (N + 1) Dim strN2 As String strN2 = "Sheet1!$B$1:$B$" & (N + 1) Range(strN).Select ActiveSheet.Shapes.AddChart2(227, xlLine).Select ActiveChart.SetSourceData Source:=Range(strN2) End Sub
2、实现自动刷新
Sub Refresh() '不断更新a的值 Dim a As Single Dim Savetime As Single Dim k As Integer For k = 1 To 1000 If i Mod 10 = 0 Then a = k '更新 y 的值 Dim x As Single Dim j As Integer For j = 1 To 1001 x = Cells(j, 1) Cells(j, 2) = (x * x) ^ (1 / 3) + 0.9 * (3.3 - x * x) ^ (1 / 2) * Sin(a * x) Next j = j + 1 '等待一会再执行下一次循环 'Application.Wait (Now + TimeValue("0:00:03")) Savetime = Timer While Timer < Savetime + 0.01 DoEvents '转让控制权' Wend End If Next k = k + 1 End Sub
相关链接:http://python.jobbole.com/81185/
posted on 2019-01-07 14:05 wangzhiliang 阅读(1039) 评论(0) 编辑 收藏 举报