【问题标题】:New function in Excel using VBA使用 VBA 的 Excel 中的新函数
【发布时间】:2019-07-27 04:58:00
【问题描述】:

首先,这是我第一次尝试在excel 中使用vba。我对此一无所知。

我尝试在excel 中创建一个新函数,以在特定单元格中设置一个值。

我有这个模块:

Public Function SETVALUE(cell As Range, newValue As Integer) As String

    cell.value = newValue

    SETVALUE = "-"

End Function

这是我的模块:

如果我在单元格A1 中输入:=SETVALUE(A2, 1),它将不起作用。

在单元格A1 中出现#Value! 而在单元格A2 中什么也没有出现。

【问题讨论】:

  • 工作表调用的函数不能修改另一个单元格的值。
  • 我会说这样做可能不是一个好主意,但有可能,请参阅here
  • @ScottCraner 所以,我做不到?

标签: excel vba


【解决方案1】:

试试这个

Option Explicit

Public Function SETVALUE(cell As Range, newValue As Integer) As String

    Evaluate "mySetValue( " & Chr(34) & cell.Address & Chr(34) & "," & Chr(34) & newValue & Chr(34) & ")"
    SETVALUE = "-"

End Function


Sub mySetValue(cell As String, newValue As Integer)
    Dim rg As Range
    Set rg = Range(cell)
    rg.Value2 = newValue
End Sub

更新:图片如何使用

【讨论】:

  • 您输入的公式包含错误:=SETVALUE(A2, 1)
  • 什么意思?
  • 我将该公式输入A1,然后按回车键并得到该错误:The formula you typed contains an error。另外,在模块中,在输入Range 之后,它会变成range
  • 我的错误我把, 放在A2, 1。它必须是;。谢谢!
【解决方案2】:

看到这里this article 说:

工作表单元格中的公式调用的用户定义函数不能 更改 Microsoft Excel 的环境。这意味着这样一个 函数不能执行以下任何操作:插入、删除或格式化 电子表格上的单元格。 更改另一个单元格的值

解决方法是通过一个子程序 像这样

Public Function SETVALUE(cell As Range, newValue As Integer) As String

Dim updateCell As String

SETVALUE = "-"

updateCell = "updateRange(" & cell.Address(False, False) & "," & newValue & ")"
Evaluate (updateCell)

End Function

Sub updateRange(vCell As Range, vNewValue As Integer)

vCell = vNewValue

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    相关资源
    最近更新 更多