With Excel, trying to find genuine used range from external HTA

前端 未结 1 1075
死守一世寂寞
死守一世寂寞 2021-01-22 02:02

I\'ve been using this command:

LastRow = ActiveSheet.UsedRange.Rows.Count

But the UsedRange property can often be inaccurate. So I\'m looking f

相关标签:
1条回答
  • 2021-01-22 02:12

    It looks like you already have your worksheet open and active? In that case:

    Const xlByRows = 1
    Const xlPrevious = 2
    
    Set objExcel = GetObject(,"Excel.Application")
    LastRow = objExcel.ActiveSheet.Cells.Find("*", , , , xlByRows, xlPrevious).Row
    

    See my recent post about using VBScript to call an Excel function for additional tips.

    When you're programming using VBA within Excel then Cells is a native object that you can reference directly. But when you're outside of Excel -- in an HTA or WSH script -- your script has no idea what Cells refers to. The only Excel objects you have are the ones you create. So you must work your way down the chain, from your main Excel (Application) object to a workbook and then to a sheet before you can operate on the Cells property. It might make more sense if you use the same names Excel does:

    ' Define the same objects that Excel does...
    Set Application = GetObject(, "Excel.Application")
    Set ThisWorkbook = Application.ActiveWorkbook
    
    ' Now get a sheet based on its name ("Sheet1", in this example)..
    Set MySheet = ThisWorkbook.Sheets("Sheet1")
    
    ' And operate on the Cells collection...
    MySheet.Cells.Find(...)
    

    As a shortcut, Excel provides an ActiveSheet property that you can use directly on the Application object to get the current sheet, essentially bypassing the workbook layer. That's what I've used in my first code snippet.

    0 讨论(0)
提交回复
热议问题