VBA实战(Excel)(4):实用功能整理

news/2024/9/22 16:48:32/

 1.后台打开Excel

       用于查数据,工作中要打开多个表获取数据再关闭的场景,利用此函数可以将excel表格作为后台数据库查询,快速实现客户要求,缺点是运行效率不够高。

Sub openexcel(exl_name As String)If Dir(addr, 16) = Empty Thenfile_error = TrueExit SubEnd IfSet fso = CreateObject("Scripting.FileSystemObject").GetFolder(addr & "\")file_name = ""For Each file In fso.FilesIf InStr(file.Name, exl_name & ".") > 0 And exl_name <> "" And InStr(file.Name, "$") < 1 Thenfile_name = file.Name 'fso.path'Debug.Print file.NameEnd IfNextSet fso = NothingIf InStr(file_name, "xlsm") > 0 And InStr(file_name, "蝶阀") > 0 Thenvba_s = TrueElsevba_s = FalseEnd IfIf file_name <> "" Thenstr_path = addr & "\" & file_name'Debug.Print str_pathIf IsWbOpen1(str_path) Then '判断excel是否已经打开ElseSet wb = GetObject(str_path)Application.Windows(wb.Name).Visible = Falsefind_if_open = TrueEnd IfElseMsgBox "报错:工作区中不存在该文件"file_error = TrueExit SubEnd If

 2.判断文件是否已打开

  避免重复打开客户已经打开的文件,提升体验和效率

Function IsWbOpen1(strPath As String) As Boolean'如果目标工作簿已打开则返回TRUE,否则返回FALSEDim oi As IntegerFor oi = Workbooks.Count To 1 Step -1If Workbooks(oi).FullName = strPath Then Exit ForNextIf oi = 0 ThenIsWbOpen1 = FalseElseIsWbOpen1 = TrueEnd If
End Function

3.生成新Excel

针对需要把结果生成一张新表格的客户

Public Sub export_excel(control As Office.IRibbonControl)Dim sourceWorkbook As WorkbookDim targetWorkbook As WorkbookDim sourceSheet As WorksheetDim newFileName As Stringshtn = Sheets("参数").Cells(2, 2)' 设置源工作簿和工作表Set sourceWorkbook = ThisWorkbook ' 当前工作簿Set sourceSheet = sourceWorkbook.Sheets("扭矩查询") ' 要导出的工作表名称' 创建新的工作簿Set targetWorkbook = Workbooks.Add' 拷贝工作表到新工作簿sourceSheet.Copy before:=targetWorkbook.Sheets(1)' 设置新工作簿的文件名newFileName = shtn & "factory-" & Format(Now(), "YYYYMMDDhhmmss") & ".xlsx" ' 新文件名' 保存新工作簿With targetWorkbook.SaveAs Filename:=ThisWorkbook.Path & "\" & newFileName, FileFormat:=xlOpenXMLWorkbook.Close SaveChanges:=FalseEnd With' 清理Set sourceSheet = NothingSet targetWorkbook = NothingSet sourceWorkbook = Nothing
End Sub

4.延时

针对需要等待的场景,比如等待加载

Public Declare PtrSafe Function timeGetTime Lib "winmm.dll" () As Long
'------------延时------------
Sub delay1(T As Single) '秒级的延时Dim time1 As Singletime1 = TimerDoDoEventsLoop While Timer - time1 < T
End SubSub delay(T As Single) '毫秒级的延时(需要引用dll)Dim time1 As Singletime1 = timeGetTimeDoDoEventsLoop While timeGetTime - time1 < T
End Sub
'------------延时------------

5.链接Access数据库

Sub ExportDataToAccess(arrFileds As Variant, datas As Variant, sheetName As String)Dim conString$, sqlString$Dim cnn, rstSet cnn = CreateObject("ADODB.Connection")  ' 创建连接对象Set rst = CreateObject("ADODB.Recordset")   ' 创建记录集对象conString = "provider=Microsoft.ace.OLEDB.12.0;Data Source=" & ThisWorkbook.path _& "\test.accdb;"cnn.Open conString  ' 连接Access数据库rst.Open "select * from " & sheetName & " where 1=2", cnn, adOpenDynamic, _adLockOptimisticrst.AddNew arrFileds, datas     '数组插入到Accesscnn.Close   ' 关闭连接对象
End Sub

6.调节图片长宽比

此函数能调节插入图片的长宽比,通过等边距裁剪,使图片在Excel中排版统一

'--------------------------调整图片长宽比---------------------------
Sub change_sacle(shp As Shape, scal As Double) 'scale为长宽比,推荐值1.5If shp.Type = 13 Then '当shape对象类型是图片的时候,才开始统计(图片的值13)Dim xCrop As Object, xl As Double, xt As Doubleshp.ScaleHeight 0.995, msoTrue, msoScaleFromTopLeftshp.ScaleWidth 1.05, msoTrue, msoScaleFromTopLeftshp.PictureFormat.Crop.PictureOffsetX = 0shp.PictureFormat.Crop.PictureOffsetY = 0shp.PictureFormat.Crop.ShapeWidth = shp.PictureFormat.Crop.PictureWidthshp.PictureFormat.Crop.ShapeHeight = shp.PictureFormat.Crop.PictureHeightIf shp.Width / shp.Height - scal > 0.05 Or scal - shp.Width / shp.Height > 0.05 Then '允许一些误差防止无限裁剪
'                    Debug.Print "执行"If shp.Width / shp.Height > scal Then '宽了,裁剪左右xl = (shp.Width - shp.Height * scal) / 2'Debug.Print xlSet xCrop = shp.PictureFormat.Crop '返回一个Crop对象With xCrop '设置裁剪格式'.ShapeLeft = shp.Left + xl '裁剪左边.ShapeWidth = .PictureWidth - 2 * xl '裁剪宽度.PictureOffsetX = 0.PictureOffsetY = 0End WithElse '高了,裁剪上下xt = (shp.Height - shp.Width / scal) / 2'Debug.Print xt
'                    Debug.Print "高了"Set xCrop = shp.PictureFormat.Crop '返回一个Crop对象With xCrop '设置裁剪格式'.ShapeTop = shp.Top + xt '裁剪顶部.ShapeHeight = .PictureHeight - 2 * xt '裁剪高度.PictureOffsetX = 0.PictureOffsetY = 0End WithEnd IfEnd IfEnd If
End Sub
'--------------------------调整图片长宽比---------------------------

7.获取一段函数的运行时间

'------------获取一段函数运行时间------------
Sub GetRunTime()Dim i As LongDim dteStart As DateDim strTime As String'Application.ScreenUpdating = False'关闭屏幕刷新dteStart = Timer'---------运行过程主体-------
MkDir "D:\Bomad\Assembly"'---------运行过程主体-------strTime = Format((Timer - dteStart), "0.00000")MsgBox "运行过程: " & strTime & "秒"'Application.ScreenUpdating = True'打开屏幕刷新
End Sub
'------------获取一段函数运行时间------------

持续更新中......


http://www.ppmy.cn/news/1466813.html

相关文章

一千题,No.0037(组个最小数)

给定数字 0-9 各若干个。你可以以任意顺序排列这些数字&#xff0c;但必须全部使用。目标是使得最后得到的数尽可能小&#xff08;注意 0 不能做首位&#xff09;。例如&#xff1a;给定两个 0&#xff0c;两个 1&#xff0c;三个 5&#xff0c;一个 8&#xff0c;我们得到的最…

二手笔记本怎么买

用途&#xff1a; 1.给爹妈用来简单办公&#xff0c;只是用office基础办公软件&#xff0c;无出差无游戏无画图需求。 预算&#xff1a; 1000以内 以下是电脑对比选项&#xff1a; 屏幕大小-> 目前市面上的尺寸对比&#xff0c;以A4纸说明&#xff0c;13.3寸14.1寸15.6…

ScrollViewer—WPF滚动条控件

ScrollViewer—WPF滚动条控件 参考地址&#xff1a;ScrollViewer 概述 - WPF .NET Framework | Microsoft Learn 1.ScrollViewer定义与功能 ScrollViewer是WPF应用程序的一个容器控件&#xff0c;用于在可以滚动的区域中显示其他可见元素。ScrollViewer封装&#xff1b; 水平…

04.docker的主要组成部分

docker体验 docker是传统的CS架构分为docker client和docker server,跟mysql一样 查看版本命令&#xff1a;docker version 查看docker下载的是社区版,ce代表社区 rpm -qa |grep docker 查看docker系统命令 docker system docker info&#xff08;如果要做监控&#xff…

基于Python的农业统计数据可视化系统设计与实现

基于Python的农业统计数据可视化系统设计与实现 Design and Implementation of Agricultural Statistical Data Visualization System Based on Python 完整下载链接:基于Python的农业统计数据可视化系统设计与实现 文章目录 基于Python的农业统计数据可视化系统设计与实现摘…

C# 控制流语句详解

C#提供了多种控制流语句&#xff0c;允许开发者根据不同的条件执行不同的代码分支。本篇博客将详细介绍if-else、switch、while、do-while、for、foreach循环&#xff0c;以及break、continue、goto、return语句。 if-else 语句 if-else语句用于基于条件执行不同的代码分支。…

面试题:计算机网络中的七四五是什么?

面试题&#xff1a;计算机网络中的七四五是什么&#xff1f; 计算机网络中说的七四五是指&#xff1a;OSI 七层模型、TCP/IP 四层模型、OSI 与 TCP/IP 的综合五层模型 OSI 七层模型 OSI 将计算机网络分为了七层&#xff0c;每一层抽象底层的内容&#xff0c;并遵守一定的规则…

迎七一党史知识竞赛答题怎么做

迎七一党史知识竞赛答题&#xff0c;不仅是对于党史知识的检验&#xff0c;更是对于参赛者学习态度和综合能力的考量。在参与这类竞赛时&#xff0c;我们需要做好充分的准备&#xff0c;掌握一定的答题技巧&#xff0c;才能取得好的成绩。 首先&#xff0c;我们要深入了解竞赛…