计算Excel工作簿

时间:2015-08-06 18:22:19

标签: excel vbscript

我正在尝试编写一个VBScript,它打开一个Excel文件并计算A列中包含数据的所有行。计数部分是我正在努力的,因为VBA中使用的许多内置函数在VBScript中不起作用。

3 个答案:

答案 0 :(得分:1)

有蛮力方法。它将起作用(不优雅或有效),但它将为一个合理大小的文件完成工作。

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

让我知道这是否有效。

答案 1 :(得分:1)

仍然可以通过应用程序对象访问

WorksheetFunctions 试试这个(我正在跳过开头部分):

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将为您提供给定范围内的非空单元格数。 (但它不会停留在第一个空单元格上。)

答案 2 :(得分:1)

Excel's COUNTA() worksheet function counts the number of non-blank cells in a range. Combine that with the VBA Evaluate() function to call COUNTA() and return the result to your script. 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)")