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

风流意气都作罢 提交于 2019-12-02 02:16:35
Bond

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!