Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

excel - Use ActiveCell.Offset(0, 3).Value in a Module to set/change the Value

I am new to VBA. Why can't I use following line in a module? But the same line seems to work fine in a sub

ActiveCell.Offset(0, 3).Value = "test"

Excel Sheet

Function trimto25(ByVal r As String) As String
    Dim i As Long
    Dim arr As Variant
    Dim erg As Variant
    
    arr = Split(r, " ")
    erg = arr(0)
    
    For i = 1 To UBound(arr)
    If (Len(erg + " " + arr(i)) < 25) Then erg = erg + " " + arr(i) Else: 
    Exit For
    Next i
    
    trimto25 = erg
    ActiveCell.Offset(0, 3).Value = "test"    
End Function

ERROR-CODE in Excel Sheet: #Value!

This seems to work fine: (But why does it work in the sub and not the function)

Sub s()
    ActiveCell.Offset(0, 3).Value = "test"
End Sub
question from:https://stackoverflow.com/questions/65845377/use-activecell-offset0-3-value-in-a-module-to-set-change-the-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This cannot be done. User defined functions cannot change the state of the workbook/worksheet, cell, ecc. Use subroutine instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...