计算单元格值

时间:2015-11-22 22:54:15

标签: excel vba excel-2013

我正在尝试编写VBA代码,用于从不同的工作表中读取值,然后计算当前值中的值。我写的代码:

Function tell_me2()
Dim my_range As Range
Dim sheet_number As Integer
Dim my_row As Integer
Dim my_column As Integer
Dim my_value As Integer
sheet_number = ActiveSheet.Index
my_row = ActiveCell.Row
my_column = ActiveCell.Column
'MsgBox (sheet_number)
'MsgBox (my_row)
'MsgBox (my_column)
'MsgBox (Worksheets(sheet_number - 1).Cells(my_row, my_column - 1))
my_value = Worksheets(sheet_number - 1).Cells(my_row, my_column - 1)
'my_value = my_range.Value
MsgBox ("12 " & my_value)
'my_range = Worksheets(sheet_number - 1).Cells(my_row - 1, my_column - 1)
'my_range.Activate
Set my_range = Worksheets(sheet_number).Cells(my_row, my_column + 1)
' have also tried
Worksheets(sheet_number).Cells(my_row, my_column + 1) = my_value - 12
my_range.Value = my_value - 12
MsgBox ("All Done!")
End Function

调试时我可以看到my_value包含正确的值,但后来我得到一个#VALUE错误,而不是正确单元格中我想要的值。

有人可以指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

您只是错过了函数的输出,在VBA中,它就像这样:

Name_of_the_Function = OutPut

OutPut可以是任何类型的变量,因此您的代码将如下所示:

Sub tell_me2()
Dim my_range As Range
Dim sheet_number As Integer
Dim my_row As Long
Dim my_column As Long
Dim my_value As Integer

sheet_number = ActiveSheet.Index
my_row = ActiveCell.Row
my_column = ActiveCell.Column

my_value = Worksheets(sheet_number - 1).Cells(my_row, my_column - 1)


Set my_range = Worksheets(sheet_number).Cells(my_row, my_column + 1)
MsgBox my_range.Address
my_range.Value = my_value - 12


MsgBox ("All Done!")
End Sub