简体   繁体   English

Excel将公式输入单元格

[英]Excel enter formula into cell

Function bd()

    Sheets("sheet1").Range("A1").value=1

End Function

This is my function. 这是我的职责 Why is it that when i enter =bd() into any cell in sheet1, the data in A1 does not change to 1? 为什么当我在sheet1的任何单元格中输入=bd() ,A1中的数据不会变为1? I do not want to use the button to change the value. 我不想使用按钮来更改值。

Why it does not work: 为什么不起作用:

If you're calling your function from an Excel formula, your function becomes a User-Defined-Function (=UDF). 如果从Excel公式调用函数,则该函数将成为用户定义的函数(= UDF)。

UDF have to follow special rules - the main one being that it cannot by any means change anything in Excel - it shall only return a value! UDF必须遵循特殊的规则-主要规则是它不能以任何方式更改Excel中的任何内容-它只能返回一个值! Your function clearly violates this rules. 您的功能显然违反了此规则。

(For reference: the other main restriction is that it shall also not access any data outside the parameters that were passed to it when calling the function. Thus, you cannot use MyUDF=Range("A1").Value - but only something like MyUDF=rngParam1.Value*2 ! (仅供参考:另一个主要限制是,调用函数时,它也不应访问传递给它的参数之外的任何数据。因此,不能使用MyUDF=Range("A1").Value只能使用类似MyUDF=rngParam1.Value*2

Alternative approach: 替代方法:

If you want to change the worksheet but don't want to use a button, you need to think of some kind of trigger event. 如果要更改工作表但不想使用按钮,则需要考虑某种触发事件。 Look at the possible Worksheet and workbook events - you'll find a list of events here - and detailed instruction how to use them here . 看看可能的工作表和工作簿事件-你会发现事件的列表在这里 -并详细说明如何使用它们在这里

For instance, you could use the Activate of Sheet1. 例如,您可以使用Sheet1的Activate For this place this code in the Sheet1 code module: 为此,将此代码放入Sheet1代码模块中:

Private Sub Worksheet_Activate()
    Range("A1").Value = 1
End Sub

Now every time that sheet1 gets activated, A1 will be reset! 现在,每次激活sheet1时,A1将被重置!

Try This 尝试这个

Copy this code on your 'Thisworkbook' on vba 将此代码复制到您在vba上的“此工作簿”中

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
If ActiveSheet.Range("A1").Value = "bd()" Then
Sheets("sheet1").Range("A1").Value = 1
End If
End Sub

Now if you enter 'bd()' (without Quotes) on cell A1 on Any Sheet and press enter the cell A1 of Sheet one will Change to 1 现在,如果您在任何工作表的单元格A1上输入“ bd()”(不带引号)并按Enter,则工作表1的单元格A1将更改为1

OR 要么

Copy this code on your 'Thisworkbook' on vba 将此代码复制到您在vba上的“此工作簿”中

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
If Sheets("sheet1").Range("A1").Value = "bd()" Then
Sheets("sheet1").Range("A1").Value = 1
End If
End Sub

Now if you enter 'bd()' (without Quotes) on cell A1 on Sheet one and press enter the cell A1 of Sheet one will Auto Change to 1 现在,如果您在工作表1的单元格A1上输入“ bd()”(不带引号),然后按Enter,工作表1的单元格A1将自动更改为1

Hope this works 希望这行得通

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM