VBScript - 找到 Excel 中的最后一行


本文主要記錄,使用 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

參考閱讀:

  1. 5 Different Ways to Find The Last Row or Last Column Using VBA — The Spreadsheet Guru
  2. Find bottom of a column in Excel using VBScript - Stack Overflow
  3. Microsoft Excel Constants [Excel 2003 VBA Language Reference] | Microsoft Docs



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM