How to use Excel worksheet functions in VBScript?

你说的曾经没有我的故事 提交于 2020-01-29 09:57:11

问题


I need to count the number of active cells in column A of Excel.
I can achieve this easily using 'worksheetfunction.countA' in Excel VBA, but unable to get the same in VBScript.

I have tried the following code:

Dim objXl , objWorkbook, objSheet ,numofactivecells

Set objXl = createobject("Excel.Application")

set objWorkbook= objXl.Workbooks.open("C:\Users\Username\Desktop\filename.xlsm")
'change filename

set objSheet = objWorkbook.Worksheets(1)

objXl.visible = true

objsheet.cells(1,1).select

numofactivecells = objsheet.WorksheetFunction.CountA(Range("A:A"))

msgbox numofactivecells

I need count of cells containing data in column A stored in variable.

I get the following error messages when I execute the code:

Microsoft VBScript compilation error: Expected identifier

Microsoft VBScript compilation error: Expected ')'


回答1:


A few mistakes:

  1. WorksheetFunction is a method of the Excel.Application object, not Worksheet.
  2. Range can't be used by itself, it's a method of a Worksheet object.

Here's code that will work:

Dim objXl
Dim objWorkbook
Dim objSheet
Dim iActiveCells

Set objXl = CreateObject("Excel.Application")
Set objWorkbook = objXl.Workbooks.open("C:\Temp\test2.xlsx") 'change filename
Set objSheet = objWorkbook.Worksheets(1)

objXl.Visible = True

With objSheet
    .Cells(1, 1).Select
    iActiveCells = objXl.WorksheetFunction.CountA(.Range("A:A"))
End With

MsgBox iActiveCells


来源:https://stackoverflow.com/questions/58463580/how-to-use-excel-worksheet-functions-in-vbscript

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