简体   繁体   English

计算行数,直到Excel工作簿中的空白文本为止

[英]Count number of rows until blank text in Excel workbook

I am trying to write a VBScript which opens up an Excel file and counts all the rows in column A which have data in it. 我正在尝试编写一个VBScript,它将打开一个Excel文件并计算A列中所有包含数据的行。 The counting part is what I am struggling with, as many built-in functions used in VBA do not work in VBScript. 计数部分是我正在努力解决的问题,因为VBA中使用的许多内置函数在VBScript中不起作用。

There's the brute force method. 有蛮力法。 It will work (not elegantly or efficiently) but it'll get the job done for a reasonably sized file. 它可以工作(不是优雅或高效的),但是可以完成大小合理的文件的工作。

Dim xlApp, xlBook, nonBlankCount
Set xlApp = CreateObject("Application.Excel")
Set xlBook = xlApp.Workbooks.Open("C:\File\Path\Workbookname.xlsx")

xlApp.Visible = True
xlBook.Sheets("Sheet1").Activate
xlBook.Range("A1").Select
nonBlankCount = 0

Do Until xlBook.Activecell = vbNullString
    nonBlankCount = nonBlankCount + 1
    Activecell.Offset(1, 0).Select
Loop

Msgbox nonBlankCount

Let me know if this works. 让我知道这个是否奏效。

WorksheetFunctions are still accessible through the application object. 仍可通过应用程序对象访问WorksheetFunctions
Try this (I am skipping the opening part): 试试这个(我跳过了开头部分):

dim app, ws, rng
set app = getobject(, "Excel.Application")
set ws = app.activeworkbook.worksheets(1)
set rng = app.Intersect(ws.UsedRange, ws.Columns(1))
msgbox app.WorksheetFunction.CountA(rng)

CountA will give you the number of non-empty cells in a given range. CountA将为您提供给定范围内的非空单元格数。 (yet it will not stop on the first empty cell.) (但它不会在第一个空单元格上停止。)

Excel's COUNTA() worksheet function counts the number of non-blank cells in a range. Excel的COUNTA()工作表函数计算范围内非空白单元格的数量。 Combine that with the VBA Evaluate() function to call COUNTA() and return the result to your script. 将其与VBA Evaluate()函数结合使用以调用COUNTA()并将结果返回到脚本中。 Then, it becomes this easy: 然后,变得很容易:

Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Open "c:\path\to\your\workbook.xlsx"

WScript.Echo "Rows with data in column A = " & objExcel.Evaluate("=COUNTA(A:A)")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM