简体   繁体   中英

How can I calculate a formula in Excel VBA and put its value in a variable? For example I want to set x equal to COUNTA(Sheet1!A:A)

How can I calculate a formula in Excel VBA and put its value in a variable?
For example I want to set x equal to COUNTA(Sheet1!A:A)

When I write x=WorksheetFunction.COUNTA(Sheet1!A:A) I get the error

"Expected: list separator or )"

You aren't passing the range reference to the worksheet function properly. You need to use a VBA style reference not a worksheet style reference.

'VBA style using worksheet codename
x = WorksheetFunction.COUNTA(Sheet1.Range("A:A"))

'VBA style using worksheet name
 x = WorksheetFunction.COUNTA(Worksheets("Sheet1").Range("A:A"))

The function needs a Range , so:

Sub kount()
    Dim r As Range, x As Long

    Set r = Sheets("Sheet1").Range("A:A")

    With Application.WorksheetFunction
        x = .CountA(r)
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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