Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA在工作表中自己的函数,用于更改工作表上的值_Vba_Excel_Excel Formula_Excel 2010 - Fatal编程技术网

Excel VBA在工作表中自己的函数,用于更改工作表上的值

Excel VBA在工作表中自己的函数,用于更改工作表上的值,vba,excel,excel-formula,excel-2010,Vba,Excel,Excel Formula,Excel 2010,我试图在Excel工作表中使用我自己的VBA函数,该函数带有返回值,同一个函数操作同一工作表或其他工作表上的单元格,但结果是值!Office Prof Plus 2010的最小工作示例,32位: Function abc() As Integer Dim i% i = 0 Sheet1.Cells(1, 2).Value = 2 abc = i End Function 当我执行Debug.Print abc时,它显然会向单元格B2写入一个2,打印的结果是0。我现在想做

我试图在Excel工作表中使用我自己的VBA函数,该函数带有返回值,同一个函数操作同一工作表或其他工作表上的单元格,但结果是值!Office Prof Plus 2010的最小工作示例,32位:

Function abc() As Integer
   Dim i%
   i = 0
   Sheet1.Cells(1, 2).Value = 2
   abc = i
End Function
当我执行Debug.Print abc时,它显然会向单元格B2写入一个2,打印的结果是0。我现在想做的是在活页1的单元格A1中=abc,但我只得到值!。顺便说一句,如果Application.EnableEvents和Application.Calculation分别被禁用,它也不起作用。设置为手动


两个问题:为什么?你知道怎么解决吗?Thx.

这种从单元格内调用的用户定义函数不能修改单元格值,只能将值返回到包含自定义项的单元格。

众所周知,除了包含自定义项的单元格外,不能使用其他自定义项更新工作表。然而,有一个非常糟糕的解决方法,每次您对工作表进行更改时都会进行检查,如果您的函数恰好是=abc,则会在B1中为您放置一个2

在标准模块中使用虚拟函数

Public Function abc() As Integer
    abc = 0
End Function
然后在Sheet1模块中输入以下代码

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub

    If Target.Formula = "=abc()" Then
        Me.Cells(1, 2).Value = 2
    End If
End Sub

请注意,在解决方法中,有一个问题bug?评估运行两次。为了解决这个问题