热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

用函数添加两个数字-Addingtwonumberswithafunction

IamwritingVBAcodetoaddtwonumbers:我正在编写VBA代码来添加两个数字:OptionExplicitDimxAsInteger,yA

I am writing VBA code to add two numbers:

我正在编写VBA代码来添加两个数字:

Option Explicit

Dim x As Integer, y As Integer
Function addtwo(x, y)
addtwo = x + y    
End Function

This is not a good function since I have to manually input the values x and y to get for the result. How can I modify the codes so it can work with any two numbers, no matter integers or numbers with decimals?

这不是一个好的功能,因为我必须手动输入值x和y来获得结果。如何修改代码,以便它可以使用任意两个数字,无论是整数还是带小数的数字?

2 个解决方案

#1


3  

You define your input variables in the FUNCTION declaration line, not above it. I would recommend the vartype DOUBLE for whole numbers and decimals.

您可以在FUNCTION声明行中定义输入变量,而不是在它上面。我建议使用整数和小数的vartype DOUBLE。

Function ADDTWO(ByVal x As Double,ByVal  y As Double) As Double
    ADDTWO = x + y
End Function

Now this function can be used in a cell as:

现在这个函数可以在单元格中用作:

=ADDTWO(3, 6)
or
=ADDTWO(A2, B7)

= ADDTWO(3,6)或= ADDTWO(A2,B7)

It can also be used in VBA.

它也可以用在VBA中。

Of course, the SUM() function does this same thing, so....I presume this is a learning exercise.

当然,SUM()函数也做同样的事情,所以....我认为这是一个学习练习。

#2


2  

As far as working with any two numbers, try the Variant data type instead of Integer. Not sure what you mean by manually inputting the values - are you talking about getting them from the worksheet?

至于使用任何两个数字,请尝试Variant数据类型而不是Integer。通过手动输入值不确定您的意思 - 您是在谈论从工作表中获取它们吗?


推荐阅读
author-avatar
云彩熨衣裳
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有