【Excel】【VBA】Reaction超限点筛选与散点图可视化

embedded/2025/1/23 21:08:17/

【Excel】【VBA】Reaction超限点筛选与散点图可视化

在这里插入图片描述

功能概述

这段代码实现了以下功能:

  1. 从SAFE输出的结果worksheet通过datalink获取更新数据
  2. 从指定工作表中读取数据
  3. 检测超过阈值的数据点
  4. 生成结果表格并添加格式化
  5. 创建可视化散点图
  6. 显示执行时间

流程图

初始化
开始
读取数据
检测超限值
是否有超限点?
创建结果表格
添加格式化
创建散点图
恢复Excel设置
显示执行时间
结束

关键方法详解

1. 性能优化技巧

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
  • 禁用屏幕更新和自动计算,提高执行效率
  • 完成后需要恢复这些设置

2. 数组操作

dataArray = .Range(.Cells(1, 1), .Cells(lastRow, 10)).Value
ReDim Preserve results(1 To 10, 1 To itemCount)
  • 使用数组批量读取数据,比逐单元格读取更快
  • ReDim Preserve 允许动态调整数组大小同时保留现有数据

3. 错误处理

On Error Resume Next
' 代码块
On Error GoTo 0
  • 使用错误处理确保代码稳定性
  • 可以优雅地处理工作表不存在等异常情况

4. 条件格式化

formatRange.FormatConditions.AddDatabar
With formatRange.FormatConditions(1).BarFillType = xlDataBarFillSolid.BarColor.Color = RGB(255, 0, 0)
End With
  • 添加数据条来可视化超限比率
  • 使用RGB颜色定义来设置格式

5. 图表创建

Set chtObj = wsResult.ChartObjects.Add(...)
With chtObj.Chart.ChartType = xlXYScatter.SeriesCollection.NewSeries' 设置数据源和格式
End With
  • 使用ChartObjects创建图表对象
  • 设置图表类型、数据源和格式化选项

6. 数据标签

With .DataLabels.ShowValue = False.Format.TextFrame2.TextRange.Font.Size = 8For pt = 1 To .Count.Item(pt).Text = Format(wsResult.Cells(pt + 1, "M").Value, "0.00%")Next pt
End With
  • 为散点添加自定义数据标签
  • 使用Format函数格式化百分比显示

学习要点

  1. 数据处理效率

    • 使用数组批量处理数据
    • 禁用不必要的Excel功能提升性能
  2. 代码结构

    • 使用With语句块简化代码
    • 合理组织代码逻辑,提高可读性
  3. 错误处理

    • 在关键操作处添加错误处理
    • 确保程序稳定运行
  4. Excel对象模型

    • 理解工作表、单元格范围的操作
    • 掌握图表对象的创建和设置
  5. 可视化技巧

    • 条件格式化的应用
    • 散点图的创建和自定义

实用技巧

  1. 使用常量定义关键值
Const THRESHOLD_VALUE As Double = 1739
  1. 计时功能实现
startTime = Timer
executionTime = Format(Timer - startTime, "0.00")
  1. 动态范围处理
lastRow = .Cells(.Rows.Count, "G").End(xlUp).Row

V20250121

Sub FindExceedingValues()Dim wsSource As Worksheet, wsCoord As Worksheet, wsResult As WorksheetDim lastRow As LongDim i As Long, itemCount As LongDim dataArray() As VariantDim results() As VariantDim startTime As DoubleConst THRESHOLD_VALUE As Double = 1739 '设置阈值变量,方便修改Dim chtObj As ChartObjectApplication.ScreenUpdating = FalseApplication.Calculation = xlCalculationManualstartTime = Timer'Set up worksheetsSet wsSource = ThisWorkbook.Worksheets("Nodal Reactions")Set wsCoord = ThisWorkbook.Worksheets("Obj Geom - Point Coordinates")'Create or clear result worksheetOn Error Resume NextSet wsResult = ThisWorkbook.Worksheets("04.Over Points List")If wsResult Is Nothing ThenSet wsResult = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))wsResult.Name = "04.Over Points List"End IfOn Error GoTo 0wsResult.Cells.Clear'Get last row of source dataWith wsSourcelastRow = .Cells(.Rows.Count, "G").End(xlUp).Row'Read all data at oncedataArray = .Range(.Cells(1, 1), .Cells(lastRow, 10)).Value'Initialize results arrayitemCount = 0ReDim results(1 To 10, 1 To 1)'Process data arrayFor i = 2 To UBound(dataArray, 1)If IsNumeric(dataArray(i, 7)) ThenIf Abs(dataArray(i, 7)) > THRESHOLD_VALUE ThenitemCount = itemCount + 1ReDim Preserve results(1 To 10, 1 To itemCount)'Store all columnsFor j = 1 To 10results(j, itemCount) = dataArray(i, j)Next jEnd IfEnd IfNext iEnd With'Write resultsWith wsResult'Write headers.Range("A1:J1") = Array("Node", "Point", "OutputCase", "CaseType", "Fx", "Fy", "Fz", "Mx", "My", "Mz").Range("K1") = "X Coordinate".Range("L1") = "Y Coordinate".Range("M1") = "Exceeding Ratio" '新增列标题'Write data if any foundIf itemCount > 0 Then'Write main dataFor i = 1 To itemCountFor j = 1 To 10.Cells(i + 1, j) = results(j, i)Next jNext i'Add VLOOKUP formulas.Range("K2").Formula = "=VLOOKUP($B2,'Obj Geom - Point Coordinates'!$A:$C,2,FALSE)".Range("L2").Formula = "=VLOOKUP($B2,'Obj Geom - Point Coordinates'!$A:$C,3,FALSE)"'添加比值计算公式.Range("M2").Formula = "=ABS(G2)/" & THRESHOLD_VALUE & "-1"'Fill down formulas if more than one rowIf itemCount > 1 Then.Range("K2:M2").AutoFill Destination:=.Range("K2:M" & itemCount + 1)End If'Format the worksheetWith .Range("A1:M1").Font.Bold = True.Interior.Color = RGB(200, 200, 200)End WithWith .Range("A1:M" & itemCount + 1).Borders.LineStyle = xlContinuous.Columns.AutoFitEnd With.Range("A:D").NumberFormat = "@".Range("M:M").NumberFormat = "0.00%" '设置比值列为百分比格式'添加数据条条件格式Dim formatRange As RangeSet formatRange = .Range("M2:M" & itemCount + 1)formatRange.FormatConditions.DeleteformatRange.FormatConditions.AddDatabarWith formatRange.FormatConditions(1).BarFillType = xlDataBarFillSolid.BarColor.Color = RGB(255, 0, 0) 'Red color.ShowValue = TrueEnd With'删除现有图表(如果存在)On Error Resume NextwsResult.ChartObjects.DeleteOn Error GoTo 0'创建散点图Set chtObj = wsResult.ChartObjects.Add( _Left:=.Range("O1").Left, _Top:=.Range("O1").Top, _Width:=800, _Height:=600)With chtObj.Chart.ChartType = xlXYScatter'添加数据系列.SeriesCollection.NewSeriesWith .SeriesCollection(1).XValues = wsResult.Range("K2:K" & itemCount + 1).Values = wsResult.Range("L2:L" & itemCount + 1).MarkerStyle = xlMarkerStyleCircle.MarkerSize = 8.Format.Fill.ForeColor.RGB = RGB(255, 0, 0)'为每个点添加数据标签.HasDataLabels = TrueWith .DataLabels.ShowValue = False.ShowCategoryName = False.ShowSeriesName = False.Format.TextFrame2.TextRange.Font.Size = 8'设置每个点的数据标签为对应的M列值On Error Resume Next  '添加错误处理Dim pt As IntegerFor pt = 1 To .Count.Item(pt).Text = Format(wsResult.Cells(pt + 1, "M").Value, "0.00%")Next ptOn Error GoTo 0End WithEnd With'设置图表标题和轴标题.HasTitle = True.ChartTitle.Text = "Distribution of Exceeding Points"With .Axes(xlCategory, xlPrimary).HasTitle = True.AxisTitle.Text = "X Coordinate"End WithWith .Axes(xlValue, xlPrimary).HasTitle = True.AxisTitle.Text = "Y Coordinate"End With'添加图例.HasLegend = FalseEnd WithEnd IfEnd With'Restore settingsApplication.ScreenUpdating = TrueApplication.Calculation = xlCalculationAutomatic'Show completion messageDim executionTime As StringexecutionTime = Format(Timer - startTime, "0.00")If itemCount = 0 ThenMsgBox "No values exceeding " & THRESHOLD_VALUE & " were found in Column Fz." & vbNewLine & _"Execution time: " & executionTime & " seconds", vbInformationElseMsgBox itemCount & " values exceeding " & THRESHOLD_VALUE & " were found and listed." & vbNewLine & _"Execution time: " & executionTime & " seconds", vbInformationEnd If
End Sub

V20250122 add lower point list (for reduncancy reference)

在这里插入图片描述

Sub FindExceedingValues()Dim wsSource As Worksheet, wsCoord As Worksheet, wsResult As Worksheet, wsResultLow As WorksheetDim lastRow As LongDim i As Long, itemCount As Long, itemCountLow As LongDim dataArray() As VariantDim results() As Variant, resultsLow() As VariantDim startTime As DoubleConst THRESHOLD_VALUE_HIGH As Double = 1850 '上限阈值Const THRESHOLD_VALUE_LOW As Double = 925  '下限阈值Dim chtObj As ChartObjectApplication.ScreenUpdating = FalseApplication.Calculation = xlCalculationManualstartTime = Timer'Set up worksheetsSet wsSource = ThisWorkbook.Worksheets("Nodal Reactions")Set wsCoord = ThisWorkbook.Worksheets("Obj Geom - Point Coordinates")'Create or clear result worksheetsOn Error Resume NextSet wsResult = ThisWorkbook.Worksheets("04.Over Points List")Set wsResultLow = ThisWorkbook.Worksheets("05.Lower Points List")If wsResult Is Nothing ThenSet wsResult = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))wsResult.Name = "04.Over Points List"End IfIf wsResultLow Is Nothing ThenSet wsResultLow = ThisWorkbook.Worksheets.Add(After:=wsResult)wsResultLow.Name = "05.Lower Points List"  ' 确保这里的名称与前面的Set语句一致End IfOn Error GoTo 0' 确保清除正确的工作表wsResult.Cells.ClearwsResultLow.Cells.Clear'Get last row of source dataWith wsSourcelastRow = .Cells(.Rows.Count, "G").End(xlUp).Row'Read all data at oncedataArray = .Range(.Cells(1, 1), .Cells(lastRow, 10)).Value'Initialize results arraysitemCount = 0itemCountLow = 0ReDim results(1 To 10, 1 To 1)ReDim resultsLow(1 To 10, 1 To 1)'Process data arrayFor i = 2 To UBound(dataArray, 1)If IsNumeric(dataArray(i, 7)) ThenIf Abs(dataArray(i, 7)) > THRESHOLD_VALUE_HIGH ThenitemCount = itemCount + 1ReDim Preserve results(1 To 10, 1 To itemCount)'Store all columns for high valuesFor j = 1 To 10results(j, itemCount) = dataArray(i, j)Next jElseIf Abs(dataArray(i, 7)) < THRESHOLD_VALUE_LOW ThenitemCountLow = itemCountLow + 1ReDim Preserve resultsLow(1 To 10, 1 To itemCountLow)'Store all columns for low valuesFor j = 1 To 10resultsLow(j, itemCountLow) = dataArray(i, j)Next jEnd IfEnd IfNext iEnd With'处理超过上限的数据ProcessWorksheet wsResult, results, itemCount, THRESHOLD_VALUE_HIGH, "Over"'处理低于下限的数据ProcessWorksheet wsResultLow, resultsLow, itemCountLow, THRESHOLD_VALUE_LOW, "Under"'Restore settingsApplication.ScreenUpdating = TrueApplication.Calculation = xlCalculationAutomatic'Show completion messageDim executionTime As StringexecutionTime = Format(Timer - startTime, "0.00")MsgBox "Found " & itemCount & " values exceeding " & THRESHOLD_VALUE_HIGH & vbNewLine & _"Found " & itemCountLow & " values below " & THRESHOLD_VALUE_LOW & vbNewLine & _"Execution time: " & executionTime & " seconds", vbInformation
End SubSub ProcessWorksheet(ws As Worksheet, results() As Variant, itemCount As Long, thresholdValue As Double, sheetType As String)Dim chtObj As ChartObjectDim j As LongWith ws'Write headers.Range("A1:J1") = Array("Node", "Point", "OutputCase", "CaseType", "Fx", "Fy", "Fz", "Mx", "My", "Mz").Range("K1") = "X Coordinate".Range("L1") = "Y Coordinate".Range("M1") = "Ratio" '新增列标题If itemCount > 0 Then'Write main dataFor i = 1 To itemCountFor j = 1 To 10.Cells(i + 1, j) = results(j, i)Next jNext i'Add VLOOKUP formulas.Range("K2").Formula = "=VLOOKUP($B2,'Obj Geom - Point Coordinates'!$A:$C,2,FALSE)".Range("L2").Formula = "=VLOOKUP($B2,'Obj Geom - Point Coordinates'!$A:$C,3,FALSE)"'添加比值计算公式If sheetType = "Over" Then.Range("M2").Formula = "=ABS(G2)/" & thresholdValue & "-1"Else.Range("M2").Formula = "=1-ABS(G2)/" & thresholdValueEnd If'Fill down formulas if more than one rowIf itemCount > 1 Then.Range("K2:M2").AutoFill Destination:=.Range("K2:M" & itemCount + 1)End If'Format the worksheetWith .Range("A1:M1").Font.Bold = True.Interior.Color = RGB(200, 200, 200)End WithWith .Range("A1:M" & itemCount + 1).Borders.LineStyle = xlContinuous.Columns.AutoFitEnd With.Range("A:D").NumberFormat = "@".Range("M:M").NumberFormat = "0.00%"'添加数据条条件格式Dim formatRange As RangeSet formatRange = .Range("M2:M" & itemCount + 1)formatRange.FormatConditions.DeleteformatRange.FormatConditions.AddDatabarWith formatRange.FormatConditions(1).BarFillType = xlDataBarFillSolidIf sheetType = "Over" Then.BarColor.Color = RGB(255, 0, 0) 'Red for over valuesElse.BarColor.Color = RGB(0, 0, 255) 'Blue for under valuesEnd If.ShowValue = TrueEnd With'删除现有图表(如果存在)On Error Resume Nextws.ChartObjects.DeleteOn Error GoTo 0'创建散点图Set chtObj = ws.ChartObjects.Add( _Left:=.Range("O1").Left, _Top:=.Range("O1").Top, _Width:=800, _Height:=600)With chtObj.Chart.ChartType = xlXYScatter'添加数据系列.SeriesCollection.NewSeriesWith .SeriesCollection(1).XValues = ws.Range("K2:K" & itemCount + 1).Values = ws.Range("L2:L" & itemCount + 1).MarkerStyle = xlMarkerStyleCircle.MarkerSize = 8If sheetType = "Over" Then.Format.Fill.ForeColor.RGB = RGB(255, 0, 0)Else.Format.Fill.ForeColor.RGB = RGB(0, 0, 255)End If'为每个点添加数据标签.HasDataLabels = TrueWith .DataLabels.ShowValue = False.ShowCategoryName = False.ShowSeriesName = False.Format.TextFrame2.TextRange.Font.Size = 8On Error Resume NextDim pt As IntegerFor pt = 1 To .Count.Item(pt).Text = Format(ws.Cells(pt + 1, "M").Value, "0.00%")Next ptOn Error GoTo 0End WithEnd With'设置图表标题和轴标题.HasTitle = TrueIf sheetType = "Over" Then.ChartTitle.Text = "Distribution of Exceeding Points"Else.ChartTitle.Text = "Distribution of Lower Points"End IfWith .Axes(xlCategory, xlPrimary).HasTitle = True.AxisTitle.Text = "X Coordinate"End WithWith .Axes(xlValue, xlPrimary).HasTitle = True.AxisTitle.Text = "Y Coordinate"End With'添加图例.HasLegend = FalseEnd WithEnd IfEnd With
End Sub

http://www.ppmy.cn/embedded/156400.html

相关文章

可替代CentOS 7的Linux操作系统选型

可替代CentOS 7的其他Linux操作系统选型 一、背景介绍二、主流操作系统调研2.1 企业级产品:Red Hat Enterprise Linux/CentOS Stream2.1.1 Red Hat Enterprise Linux2.1.2 CentOS Stream2.2 其他发行版:Debian/Ubuntu2.3 开源产品:AlmaLinux / RockyLinux2.3.1 AlmaLinux2.3…

微信小程序1.1 微信小程序介绍

1.1 微信小程序介绍 内容提要 什么是微信小程序 微信小程序的功能 微信小程序使用场景 微信小程序能取代App吗 微信小程序的发展历程 微信小程序带来的机会

基于微信小程序的科创微应用平台设计与实现(LW+源码+讲解)

专注于大学生项目实战开发,讲解,毕业答疑辅导&#xff0c;欢迎高校老师/同行前辈交流合作✌。 技术范围&#xff1a;SpringBoot、Vue、SSM、HLMT、小程序、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、安卓app、大数据、物联网、机器学习等设计与开发。 主要内容&#xff1a;…

安装auto_gptq解决办法

这个错误表明在安装 auto_gptq 包时,生成 QiGen 内核时失败了。具体来说,setup.py 脚本尝试运行一个 Python 脚本来生成内核,但该脚本不存在或无法访问。以下是一些可能的解决方案: 1. 确保依赖项已安装 首先,确保你已经安装了所有必要的依赖项。你可以尝试以下命令来安…

iOS 权限管理:同时请求相机和麦克风权限的最佳实践

引言 在开发视频类应用时&#xff0c;我们常常会遇到需要同时请求相机和麦克风权限的场景。比如&#xff0c;在用户发布视频动态时&#xff0c;相机用于捕捉画面&#xff0c;麦克风用于录制声音&#xff1b;又或者在直播功能中&#xff0c;只有获得这两项权限&#xff0c;用户…

图像处理基础(4):高斯滤波器详解

本文主要介绍了高斯滤波器的原理及其实现过程 高斯滤波器是一种线性滤波器&#xff0c;能够有效的抑制噪声&#xff0c;平滑图像。其作用原理和均值滤波器类似&#xff0c;都是取滤波器窗口内的像素的均值作为输出。其窗口模板的系数和均值滤波器不同&#xff0c;均值滤波器的…

后端之路——阿里云OSS云存储

一、何为阿里云OSS 全名叫“阿里云对象存储OSS”&#xff0c;就是云存储&#xff0c;前端发文件到服务器&#xff0c;服务器不用再存到本地磁盘&#xff0c;可以直接传给“阿里云OSS”&#xff0c;存在网上。 二、怎么用 大体逻辑&#xff1a; 细分的话就是&#xff1a; 1、准…

1.2.神经网络基础

目录 1.2.神经网络基础 1.2.1.Logistic回归 1.2.2 梯度下降算法 1.2.3 导数 1.2.4 向量化编程 1.2.5 正向传播与反向传播 1.2.6.练习 1.2.神经网络基础 1.2.1.Logistic回归 1.2.1.1.Logistic回归 逻辑回归是一个主要用于二分分类类的算法。那么逻辑回归是给定一个x ,…