Vba excel функция не возвращает значение

Just setting the return value to the function name is still not exactly the same as the Java (or other) return statement, because in java, return exits the function, like this:

public int test(int x) {
    if (x == 1) {
        return 1; // exits immediately
    }

    // still here? return 0 as default.
    return 0;
}

In VB, the exact equivalent takes two lines if you are not setting the return value at the end of your function. So, in VB the exact corollary would look like this:

Public Function test(ByVal x As Integer) As Integer
    If x = 1 Then
        test = 1 ' does not exit immediately. You must manually terminate...
        Exit Function ' to exit
    End If

    ' Still here? return 0 as default.
    test = 0
    ' no need for an Exit Function because we're about to exit anyway.
End Function 

Since this is the case, it’s also nice to know that you can use the return variable like any other variable in the method. Like this:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test <> 1 Then ' Test the currently set return value
        test = 0 ' Reset the return value to a *new* value
    End If

End Function 

Or, the extreme example of how the return variable works (but not necessarily a good example of how you should actually code)—the one that will keep you up at night:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test > 0 Then

        ' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
        ' AND THE RESULT RESETTING THE RETURN VALUE.
        test = test(test - 1)

    End If

End Function

Простое значение возвращаемого значения для имени функции все еще не совсем то же, что и оператор Java (или другого) return, потому что в java, return завершает функцию, например:

public int test(int x) {
    if (x == 1) {
        return 1; // exits immediately
    }

    // still here? return 0 as default.
    return 0;
}

В VB эквивалент точный принимает две строки, если вы не устанавливаете возвращаемое значение в конце вашей функции. Итак, в VB точное следствие будет выглядеть так:

Public Function test(ByVal x As Integer) As Integer
    If x = 1 Then
        test = 1 ' does not exit immediately. You must manually terminate...
        Exit Function ' to exit
    End If

    ' Still here? return 0 as default.
    test = 0
    ' no need for an Exit Function because we're about to exit anyway.
End Function 

Так как это так, также приятно знать, что вы можете использовать возвращаемую переменную, как и любую другую переменную в методе. Вот так:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test <> 1 Then ' Test the currently set return value
        test = 0 ' Reset the return value to a *new* value
    End If

End Function 

Или, крайний пример того, как работает возвращаемая переменная (но не обязательно хороший пример того, как вы должны на самом деле кодировать) — тот, который будет держать вас в ночное время:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test > 0 Then

        ' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
        ' AND THE RESULT RESETTING THE RETURN VALUE.
        test = test(test - 1)

    End If

End Function

I need help with this function. This function is not returning value.

Function CalcComm(salesdate As Date, salesamount As Double) As Double

If sales_A < 10000 Then
Commission = salesamount * 0.03
ElseIf salesamount >= 10000 And salesamount < 25000 Then
Commission = salesamount * 0.04
ElseIf salesamount >= 25000 Then
Commission = salesamount * 0.06
Else: Commission = salesamount * 0.06
End If

If month(saledate) = 1 Or month(saledate) = 2 Or month(saledate) = 12 Then
Commission = salesamount * 0.015

End If
End Function

braX's user avatar

braX

11.5k5 gold badges20 silver badges33 bronze badges

asked Oct 29, 2021 at 6:41

Sterling Mateo's user avatar

1

You did not assign the function the value you want to return. e.g. CalcComm = Commission.

sales_A is not declared and I believe should be salesamount, saledate is a typo and should be salesdate. Please insert Option Explicit at the top of your module to enforce variable declaration (and indirectly helps you catch typo).

Your code logic could make use of Select Case statements, the code below will return:

  • 1.5% if in the month of Jan, Feb and Dec;
  • For other months
    • 3% for < 10000;
    • 4% for 10000-25000 and;
    • 6% for >= 25000 and above.
Option Explicit

Function CalcComm(salesdate As Date, salesamount As Double) As Double
    Dim Commission As Double
    
    Select Case Month(salesdate)
        Case 1, 2, 12: Commission = salesamount * 0.015
        Case Else
            Select Case salesamount
                Case Is < 10000: Commission = salesamount * 0.03
                Case Is < 25000: Commission = salesamount * 0.04
                Case Else: Commission = salesamount * 0.06
            End Select
    End Select
    
    CalcComm = Commission
End Function

answered Oct 29, 2021 at 6:59

Raymond Wu's user avatar

Raymond WuRaymond Wu

3,3372 gold badges8 silver badges20 bronze badges

2

In addition to not returning the value in the function name, both of the If functions contain errors:

  • sales_A isn’t a value passed into the function
  • saledate should be salesdate

answered Oct 29, 2021 at 6:51

Solver Max's user avatar

Solver MaxSolver Max

3811 gold badge2 silver badges6 bronze badges

Calculate Commission (UDF)

Option Explicit

Function CalcComm( _
    ByVal SalesDate As Date, _
    ByVal SalesAmount As Double) _
As Double
    
    Dim CommRate As Double
    
    Select Case SalesAmount
    Case Is < 10000
        CommRate = 0.03
    Case Is < 25000
        CommRate = 0.04
    Case Else
        CommRate = 0.06
    End Select
    
    Select Case Month(SalesDate)
    Case 1, 2, 12
        CommRate = CommRate + 0.015
    End Select
    
    CalcComm = SalesAmount * CommRate

End Function

answered Oct 29, 2021 at 8:12

VBasic2008's user avatar

VBasic2008VBasic2008

39.8k5 gold badges17 silver badges27 bronze badges

Ципихович Эндрю

1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

1

Не возвращает данные с функции

18.12.2021, 14:17. Показов 856. Ответов 8

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

здравствуйте, в макросе Sub хххххх() посылаю в функцию, вот эта строка:

Visual Basic
1
Проверяемое_слово = "в " + справаSplit(J): Проверяем_орфографию_грамматику_слова (Проверяемое_слово)

функция

Visual Basic
1
Public Function Проверяем_орфографию_грамматику_слова(Проверяемое_слово) As String

считает, но не возвращает нужное, в чём проблема? спасибо



0



Модератор

Эксперт функциональных языков программированияЭксперт Python

34706 / 19227 / 4039

Регистрация: 12.02.2012

Сообщений: 32,183

Записей в блоге: 13

18.12.2021, 14:21

2

Ципихович Эндрю, Приведи весь код функции



0



Ципихович Эндрю

1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

18.12.2021, 14:51

 [ТС]

3

Catstail,

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Public Function Проверяем_орфографию_грамматику_слова(Проверяемое_слово) As String
 
'проверяем грамматику, точку и пробел надо ставить у проверяемого слова
    If Application.CheckGrammar(Проверяемое_слово & ". ") = True Then
        MsgBox "Проверяемое слово: " & Проверяемое_слово & " без ошибок!"
    Else
        'MsgBox$ "Проверяемое слово: " & Проверяемое_слово & " подчёркнуто зелёной волнистой линией"
        'применимо для Word 2007, бывает версия Word 2007 "12.0.4518"
        If Left$(Application.Build, 2) = "12" Then Проверка_грамматики (Проверяемое_слово)
    End If
 
End Function
 
Function Проверка_грамматики(Проверяемое_слово)
 
    Dim Doc As Document
    Set Doc = Documents.Add(, True, , False)
    Doc.Content.Text = Проверяемое_слово
    Do Until Doc.GrammarChecked
        DoEvents
    Loop
    For i = 1 To Doc.Content.Words.Count
        Doc.Content.Words(i).Select
        ПервыйЭлементКонтекстногоМеню = Doc.CommandBars("Grammar").Controls(1).Caption
        If ПервыйЭлементКонтекстногоМеню <> "&Грамматика..." Then
            Exit For
        End If
    Next
    Doc.Close False
 
    If Right$(ПервыйЭлементКонтекстногоМеню, 46) = " не связан с существительным или местоимением." Then MsgBox ПервыйЭлементКонтекстногоМеню
 
End Function

кстати Вы и в питоне разбираетесь не в курсе как там это можно сделать?
смысл, чтобы «у перекрёсток» выдало как ошибку «Предлог «ххх» не связан с существительным или местоимением.»



0



Punkt5

малоболт

1143 / 442 / 193

Регистрация: 30.01.2020

Сообщений: 1,095

18.12.2021, 15:02

4

Лучший ответ Сообщение было отмечено Catstail как решение

Решение

Ципихович Эндрю, Для того, чтобы функция возвращала значение, надо по ходу функции присвоить это значние названию файнкции. Например:

Visual Basic
1
2
3
4
5
6
Function Проверка_грамматики(Проверяемое_слово)
  Проверка_грамматики = "Jopa"
  If Проверяемое_слово = "Jopa" Then
    Проверка_грамматики = "Big Jopa"
  End If
End Function



2



bite

3699 / 3131 / 694

Регистрация: 13.04.2015

Сообщений: 7,323

18.12.2021, 16:28

5

Цитата
Сообщение от Punkt5
Посмотреть сообщение

«Big Jopa»

Шалун



0



Ципихович Эндрю

1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

19.12.2021, 14:51

 [ТС]

6

я сделал как сказали, поставил проверку в макросе после того как должна вернуться переменная:

Visual Basic
1
MsgBox$ Проверяем_орфографию_грамматику_слова

получаю мессагу Argument not optional в чём я ошибаюсь? спасибо



0



elixi

297 / 157 / 86

Регистрация: 01.04.2020

Сообщений: 436

19.12.2021, 15:04

7

Цитата
Сообщение от Ципихович Эндрю
Посмотреть сообщение

Argument not optional

Argument not optional = аргумент не необязательный = аргумент обязательный

Visual Basic
1
MsgBox$ Проверяем_орфографию_грамматику_слова(ВашАргумент)



0



малоболт

1143 / 442 / 193

Регистрация: 30.01.2020

Сообщений: 1,095

19.12.2021, 15:28

8

Цитата
Сообщение от Ципихович Эндрю
Посмотреть сообщение

Argument not optional

Означает, что аргумент в вызываемой функции/подпрограмме описан без использования слова Optional и на этом основании является обязательным при вызове. Если же вы пытаетесь вызвать эту функцию/подпрограмму без указания аргумента, и слово Optional не было использовано при описании аргумета, интерпретатор предупреждает вас о том, что ваше описание функции и ваш вызов её вошли в противоречие, которое вам следует разрешить либо с той, либо с обратной сороны.



1



Ципихович Эндрю

1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

19.12.2021, 18:53

 [ТС]

9

Punkt5, спасибо
не подскажет ли кто строки 19-28 в сообщении 3 что значат

Visual Basic
1
2
3
4
5
6
7
8
9
10
    Do Until Doc.GrammarChecked
        DoEvents
    Loop
    For i = 1 To Doc.Content.Words.Count
        Doc.Content.Words(i).Select
        ПервыйЭлементКонтекстногоМеню = Doc.CommandBars("Grammar").Controls(1).Caption
        If ПервыйЭлементКонтекстногоМеню <> "&Грамматика..." Then
            Exit For
        End If
    Next

?? спасибо



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

19.12.2021, 18:53

9

I am making an excel sheet with a specific condition that will return a string. This function worked as a sub-procedure but when I tried to use it as a function, I keep getting ‘#VALUE!’. Can someone please help me why this code is not returning the string?

Please see the code below:

Function check_input2() As String

Dim range1 As range
Dim range2 As range
Dim row_num As Integer
'Dim col_num As Integer
Dim val As Boolean
Dim a As Integer
Dim b As Integer
Dim row_end As Integer
'count = 0
'row_num = range1(1, 1).Row
'col_num = range1(1, 1).Column

a = 1
b = 1
val = True
row_end = 11 + 12

row_num = 11
Set range1 = range("A" & row_num & ":" & "A" & row_end)

For row_num = 11 To row_end
    Set range2 = range("I" & row_num & ":O" & row_num)

    If WorksheetFunction.Sum(range2.Value) = 0 Then
        'nothing has to happen
        val = val And True
        range("Q" & row_num).Value = True
    ElseIf WorksheetFunction.Sum(range2.Value) > 0 Then
        If IsEmpty(range1(a, b).Value) = True Then
        val = val And False
        range("Q" & row_num).Value = False '**************************
        ElseIf IsEmpty(range1(a, b).Value) = False Then
        val = val And True
        range("Q" & row_num).Value = True '**************************
        End If
    End If
    a = a + 1
Next

If val = True Then
    'do nothing
    'check_input2 ("hello")--error
    check_input2 = "hello"
    'check_input2 = True
ElseIf val = False Then
    'check_input2 ("Please do not skip the project number!")--error
    check_input2 = "Please do not skip the project number!"
    'check_input2 = False
End If

End Function

Понравилась статья? Поделить с друзьями:
  • Vba excel ячейка на странице
  • Vba excel функция длина строки
  • Vba excel ячейка за экраном
  • Vba excel функция ввода данных
  • Vba excel ячейка добавить текст