本文主要記錄,使用 VBScript,如何找到 Excel 頁面中的,最後一行。 參考 VBA 中的解決方式: 很多 VBA 與 VBScript 的解決方法都是通用的,尤其是針對 Excel 的時候, 所以,我們先來看下 VBA 中,常用的3中方法: VBScript 中的解決方式: 然後,我們來 ...
本文主要記錄,使用 VBScript,如何找到 Excel 頁面中的,最後一行。
參考 VBA 中的解決方式:
很多 VBA 與 VBScript 的解決方法都是通用的,尤其是針對 Excel 的時候,
所以,我們先來看下 VBA 中,常用的3中方法:
'從頁面最後一行,按 Ctrl + Up 箭頭
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
'使用 UsedRange 屬性
LastRow = sht.UsedRange.Rows(sht.UsedRange.Rows.Count).Row
'使用 SpecialCells 函數
LastRow = sht.Cells.SpecialCells(xlCellTypeLastCell).Row
VBScript 中的解決方式:
然後,我們來看下,VBScript中,要怎麼達到上面的效果,
如果,要是把上面代碼,直接放到 VBScript 中運行,就會出現位置錯誤,
這中間確實,有一個 Trick,是我之前沒註意到的,
就是,VBScript 中必須手動設置,Constant (常量),
而,VBA 中,這些常量的值,是預設的,不用設置,
那麼,來看下 VBScript 的代碼:
'先設定要使用到的 Objects(對象)
Set oExcel = GetObject(,"Excel.Application")
Set wb = oExcel.Workbooks("Book10 - Copy.xlsm")
Set sht = wb.worksheets("Data")
wb.Activate
'從頁面最後一行,按 Ctrl + Up 箭頭
Const xlUp = -4162
LastRow = sht.Cells(sht.Rows.Count, 1).End(xlUp).Row
MsgBox LastRow
'或者,使用 Range,和 Ctrl + Up 箭頭
Const xlUp = -4162
LastRow = sht.Range("G" & sht.Rows.Count).End(xlUp).Row
MsgBox LastRow
'或者,使用 UsedRange 屬性
LastRow = sht.UsedRange.Rows(sht.UsedRange.Rows.Count).Row
MsgBox LastRow
'或者,使用 SpecialCells 函數
Const xlCellTypeLastCell = 11
LastRow = sht.Cells.SpecialCells(xlCellTypeLastCell).Row
MsgBox LastRow
以上,就是 VBScript 中的實現方法,
常量的數值可以去,微軟官方文檔中去找,
常用的常量,有下麵四種,列出來供大家參考:
Constant Value
xlDownward -4170
xlHorizontal -4128
xlUpward -4171
xlVertical -4166
參考閱讀:
- 5 Different Ways to Find The Last Row or Last Column Using VBA — The Spreadsheet Guru
- Find bottom of a column in Excel using VBScript - Stack Overflow
- Microsoft Excel Constants [Excel 2003 VBA Language Reference] | Microsoft Docs