VBA 获取Sheet最大行
compared all possibilities with a long test sheet:
0,140625 sec for
lastrow = calcws.Cells.Find("*", [A1], , , xlByColumns, xlPrevious).row
0 sec for
iLastRow = calcws.Cells(rows.count, "a").End(xlUp).row
and
numofrows = calcws.Cells.SpecialCells(xlLastCell).row
0,0078125 sec for
lastrow = calcws.UsedRange.rows.count
Do While 1
If calcws.Cells(lastrow, 1).Value = "" Then
lastrow = lastrow - 1
Else
Exit Do
End If
Loop
I think the favourites are obvious...
Today’s author, Chad Rothschiller, a Program Manager on the Excel team, is back with a follow up from his previous post on VBA and Excel performance.
I want to start off this post by thanking everyone who sent in their examples in response to my January request. It is incredibly helpful to be able to look at what you all are doing with Excel! Not only did I see a huge variety in how Excel is being used, you also pointed out various tips and tricks for writing fast VBA code in Excel.
In this post I’m going to share with you the most important performance tips I know about. There are tons of sites, pages, and people who are experts as well on this subject, have performed their own tests, and shared their results and ideas. If you think I missed an important concept for how to optimize Excel VBA performance, or if you’ve got a valuable comment or link to share, please feel free to post here so everyone can benefit. Thanks!
Turn Off Everything But the Essentials While Your Code is Running
This optimization explicitly turns off Excel functionality you don’t need to happen (over and over and over) while your code runs. Note that in the code sample below we grab the current state of these properties, turn them off, and then restore them at the end of code execution.
One reason this helps is that if you’re updating (via VBA) several different ranges with new values, or copy / pasting from several ranges to create a consolidated table of data, you likely do not want to have Excel taking time and resources to recalculate formulas, display paste progress, or even redraw the grid, especially after every single operation (even more so if your code uses loops). Just one recalculation and one redraw at the end of your code execution is enough to get the workbook current with all your changes.
Here’s some sample code that shows how and what to shut off while your code runs. Doing this should help improve the performance of your code:
‘Get current state of various Excel settings; put this at the beginning of your code
screenUpdateState = Application.ScreenUpdating
statusBarState = Application.DisplayStatusBar
calcState = Application.Calculation
eventsState = Application.EnableEvents
displayPageBreakState = ActiveSheet.DisplayPageBreaks ‘note this is a sheet-level setting
‘turn off some Excel functionality so your code runs faster
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False ‘note this is a sheet-level setting
‘>>your code goes here<<
‘after your code runs, restore state; put this at the end of your code
Application.ScreenUpdating = screenUpdateState
Application.DisplayStatusBar = statusBarState
Application.Calculation = calcState
Application.EnableEvents = eventsState
ActiveSheet.DisplayPageBreaks = displayPageBreaksState ‘note this is a sheet-level setting
Here’s a quick description for each of these settings:
Application.ScreenUpdating: This setting tells Excel to not redraw the screen while False. The benefit here is that you probably don’t need Excel using up resources trying to draw the screen since it’s changing faster than the user can perceive. Since it requires lots of resources to draw the screen so frequently, just turn off drawing the screen until the end of your code execution. Be sure to turn it back on right before your code ends.
Application.DisplayStatusBar: This setting tells Excel to stop showing status while False. For example, if you use VBA to copy/paste a range, while the paste is completing Excel will show the progress of that operation on the status bar. Turning off screen updating is separate from turning off the status bar display so that you can disable screen updating but still provide feedback to the user, if desired. Again, turn it back on right before your code ends execution.
Application.Calculation: This setting allows you to programmatically set Excel’s calculation mode. “Manual” (xlCalculationManual) mode means Excel waits for the user (or your code) to explicitly initiate calculation. “Automatic” is the default and means that Excel decides when to recalculate the workbook (e.g. when you enter a new formula on the sheet). Since recalculating your workbook can be time and resource intensive, you might not want Excel triggering a recalc every time you change a cell value. Turn off calculation while your code executes, then set the mode back. Note: setting the mode back to “Automatic” (xlCalculationAutomatic) will trigger a recalc.
Application.EnableEvents: This setting tells Excel to not fire events while False. While looking into Excel VBA performance issues I learned that some desktop search tools implement event listeners (probably to better track document contents as it changes). You might not want Excel firing an event for every cell you’re changing via code, and turning off events will speed up your VBA code performance if there is a COM Add-In listening in on Excel events. (Thanks to Doug Jenkins for pointing this out in my earlier post).
ActiveSheet.DisplayPageBreaks: A good description of this setting already exists: http://support.microsoft.com/kb/199505(Thanks to David McRitchie for pointing this out).
Read/Write Large Blocks of Cells in a Single Operation
This optimization explicitly reduces the number of times data is transferred between Excel and your code. Instead of looping through cells one at a time and getting or setting a value, do the same operation over the whole range in one line, using an array variable to store values as needed.
For each of the code examples below, I had put random values (not formulas) into cells A1:C10000.
Here’s a slow, looping method:
Dim DataRange as Range
Dim Irow as Long
Dim Icol as Integer
Dim MyVar as Double
Set DataRange=Range(“A1:C10000”)For Irow=1 to 10000
For icol=1 to 3
MyVar=DataRange(Irow,Icol) ‘Read values from the Excel grid 30K times
If MyVar > 0 then
MyVar=MyVar*Myvar ‘ Change the value
DataRange(Irow,Icol)=MyVar ‘Write values back into the Excel grid 30K times
End If
Next Icol
Next Irow
Here’s the fast version of that code:
Dim DataRange As Variant
Dim Irow As Long
Dim Icol As Integer
Dim MyVar As Double
DataRange = Range(“A1:C10000”).Value ‘ read all the values at once from the Excel grid, put into an arrayFor Irow = 1 To 10000
For Icol = 1 To 3
MyVar = DataRange(Irow, Icol)
If MyVar > 0 Then
MyVar=MyVar*Myvar ‘ Change the values in the array
DataRange(Irow, Icol) = MyVar
End If
Next Icol
Next Irow
Range(“A1:C10000”).Value = DataRange ‘ writes all the results back to the range at once
Note: I first learned of this concept by reading a web page by John Walkenbach found here:http://www.dailydoseofexcel.com/archives/2006/12/04/writing-to-a-range-using-vba/
A previous Excel blog entry by Dany Hoter also compares these two methods, along with a selection / offset method as well: http://blogs.msdn.com/excel/archive/2008/10/03/what-is-the-fastest-way-to-scan-a-large-range-in-excel.aspx
…which leads me to my next point.
Avoid Selecting / Activating Objects
Notice that in the above-referenced blog post, the selection method of updating a range was the slowest. This next optimization minimizes how frequently Excel has to respond to the selection changing in the workbook by minimizing the selection changing as much as possible.
Range Example: Again, see the Excel blog post quoted above. It demonstrates that using selection is the slowest of the 3 methods discussed for reading and writing to ranges.
Shapes Example: Setup: I have 40 shapes on a sheet, and I want to write “Hello” in each of them.
Using the slower “selection” method, the code looks like this:
For i = 0 To ActiveSheet.Shapes.Count
ActiveSheet.Shapes(i).Select
Selection.Text = “Hello”
Next i
The much faster method is to avoid selection completely and directly reference the shape:
For i = 0 To ActiveSheet.Shapes.Count
ActiveSheet.Shapes(i).TextEffect.Text = “Hello”
Next i
The concepts illustrated by the examples above can also be applied to objects other than Ranges and Shapes.
Note: I first learned of this concept, in the context of shapes, by reading a web page by Ron de Bruin found here:http://www.rondebruin.nl/shape.htm
Related Performance Paper
See the “Improving Performance in Excel 2007” paper on MSDN: http://msdn.microsoft.com/en-us/library/aa730921.aspx
This is a fairly detailed and comprehensive paper that introduces the bigger grid and increased limits in Excel 2007, and primarily focuses on Excel calculation performance and debugging calculation performance bottlenecks. There’s also a short section on how to write faster VBA macros.
Other Performance Optimizations
While the above optimizations are what I consider the most important, there are a few other “honorable mention” optimizations I will mention briefly for you to consider.
Consider the performance gains by implementing your code’s functionality via XLL / C-API. An overview and supporting materials for the SDK can be found here: http://msdn.microsoft.com/en-us/library/bb687827.aspx .
Declare variables with explicit types to avoid the overhead of determining the data type (repetitively if used in a loop) during code execution.
For simple functions used by your code in high frequency, implement them yourself in VBA instead of using the WorksheetFunction object.
Use Range.SpecialCells() to scope down the number of cells your code needs to work with.
VBA 获取Sheet最大行的更多相关文章
- java使用POI获取sheet、行数、列数
FileInputStream inp = new FileInputStream("E:\\WEIAN.xls"); HSSFWorkbook wb = new HSSFWork ...
- excel 宏循环行数据 ,Excel统计所有sheet数据行数 VBA
Sub fun1() '统计每一个sheet有多少行数据 Set s1 = Sheets("Sheet1") 'totalok = 0 To Sheets.Count s1.Cel ...
- android获取textview的行数
最近项目需求,需要获取Textview的行数,通过行数与TextView的maxLines进行比较来确定是否显示TextView下方的展开按钮是否显示,废话少说直接上代码,mTextView.getL ...
- StringGrid 实例2:1、获取 StringGrid 的行数、列数; 2、给单元赋值.
实例2: 本例功能: 1.获取 StringGrid 的行数.列数; 2.给单元赋值. 运行效果图:
- js日期的写法,获取girdviw的行数、提示信息、验证数量信息
//制订日期(js日期的写法) var myDate = new Date(); var theDate = myDate.toLocaleDateString(); //获取今天的日期 //获取控 ...
- jquery easyui datagrid 获取Checked选择行(勾选行)数据
原文:jquery easyui datagrid 获取Checked选择行(勾选行)数据 getSelected:取得第一个选中行数据,如果没有选中行,则返回 null,否则返回记录. getSel ...
- displaytag如何实现获取到每行的id字段的值。
1.displaytag如何实现获取到每行的id字段的值. 使用封装好的框架,有时候,对于一个知识点不熟悉,可能会浪费你大把的时间,我使用displaytag主要是使用它的分页技术,但是客户提出的需求 ...
- Dev_GridView获取所选行的句柄
这是官方帮助文档上的一句话: 此示例演示如何获取所选行,然后更改其字段值. GetSelectedRows方法检索所选行的句柄. 由于行句柄反映了在View中显示行的顺序,因此修改单行可 能会影响其他 ...
- easyui获取正在编辑行的代码
easyui获取正在编辑行的代码……没这个真不知道怎么搞0.0可能这问题还要弄半天……卧槽 ...等于是笔记下来 : var ed = $("dg").datagrid('get ...
随机推荐
- Kafka实战-Flume到Kafka
1.概述 前面给大家介绍了整个Kafka项目的开发流程,今天给大家分享Kafka如何获取数据源,即Kafka生产数据.下面是今天要分享的目录: 数据来源 Flume到Kafka 数据源加载 预览 下面 ...
- 网络基础知识之 Ping
========================================假定主机A的IP地址是192.168.1.1,主机B的IP地址是192.168.1.2,都在同一子网内,则当你在主机A上 ...
- git版本控制管理实践-4
vcs: version control system 版本控制系统 local vcs, 集中式版本控制系统: centralized vcs; 分布式vcs: distributed vcs Lo ...
- HTML的初体验
有话先说:记得初次接触HTML代码还是在两年多前的事情,那是只是凭着一时的兴趣.却不知一入HTML深似海,再见依旧还是兴趣或许就是美好生活的必备. 不用说的是HTML是制作网页,网站开发必须要掌握并学 ...
- 使用Entity Framework通过code first方式创建数据库和数据表
开发环境 WIN10 Entity Framework6.0 MVC5.0 开发工具 VS2015 SqlServer2012 1.创建上下文Context继承DbContext,并创建其他的业 ...
- JDK source 之 ArrayList 需要注意事项
线程安全 ArrayList内部没有实现原子性操作,所以是非线程安全的.如果需要在线程安全的环境下使用List的话,需要使用Vector 或者CopyOnWriteArrayList,具体场景,自行深 ...
- 【Python基础学习三】数字(Number)
Python Number 数据类型用于存储数值. 数据类型是不允许改变的,这就意味着如果改变 Number 数据类型的值,将重新分配内存空间. Python 四种数值类型: 整型(Int) - 通常 ...
- liunx中计算机壳层
什么是shell?shell是用C语言编写的程序.既是一种命令语言,又是一种程序设计语言.shell是一种应用程序,这个应用程序提供一个界面,用户通过这个界面访问系统内核的服务.在计算机科学中,She ...
- matplotlib绘制多组 散点连线图【用于对比】待实现
绘制散点+连线图: http://www.cnblogs.com/aaronhoo/p/5150596.html http://zhidao.baidu.com/link?url=Q1b7NG8eEz ...
- poj 3687(拓扑排序)
http://poj.org/problem?id=3687 题意:有一些球他们都有各自的重量,而且每个球的重量都不相同,现在,要给这些球贴标签.如果这些球没有限定条件说是哪个比哪个轻的话,那么默认的 ...