gpt4 book ai didi

excel - 为什么我不能使用由 =hyperlink() 公式触发的 VBA 函数更改单元格中的字体?

转载 作者:行者123 更新时间:2023-12-04 21:45:06 25 4
gpt4 key购买 nike

我正在尝试在 VBA 函数 ( changeCell ) 中更改文本及其外观。

option explicit

function changeCell(txt as string, sz as long) as range

cells(4,4).value = txt
cells(4,4).font.size = sz
cells(4,4).font.bold = true
cells(4,4).font.color = rgb(255, 100, 0)

set changeCell = cells(5,5)

end function
当我调用 changeCell("foo", 20) ,文本按我的预期改变。
但是,如果从 =hyperlink() 调用此函数工作表函数, font.sizefont.bold属性没有改变(尽管 font.color.value 是)。
这是我用来在工作表上插入超链接的函数:
sub insertHyperlink()

cells(2,2).formula = "=hyperlink(""#changeCell(""""hyperlink was clicked"""", 99)"", ""click me to change cell"")"

end sub
我正在尝试使用 =hyperlink()函数,因为我需要能够将参数值传递给被调用的函数。这些值是在 =hyperlink() 时确定的。插入函数(这不会手动发生,但使用类似 insertHyperlink 的函数,尽管更精细)
我想知道为什么会这样以及如何在 =hyperlink() 调用的函数中更改字体大小.

最佳答案

以下解决方法是可能的(即使不是最好的):
我们在模块中添加单元格样式类型和公共(public)变量。

Option Explicit

Public Type TCellStyle
Text As String
Size As Long
Cell As Range
End Type

Public CellStyle As TCellStyle
然后使用您的超链接调用的以下函数 =hyperlink("#changeCell(""hyperlink was clicked"", 99)", "click me to change cell")
Public Function changeCell(txt As String, sz As Long) As Range
Dim ws As Worksheet
Set ws = Application.Caller.Parent ' get the worksheet of the hyperlink

' save the style to our public variable for later processing
With CellStyle
Set .Cell = ws.Cells(4, 4)
.Text = txt
.Size = sz
End With

' set the destination of the hyperlink (must be in the same sheet as the hyperlink because this trigger the SelectionChange event).
Set changeCell = ws.Cells(5, 5)
End Function
那么我们只需要一个 Worksheet_SelectionChange事件在所需的工作表中,让它为我们做脏活(由于限制,我们不能在 changeCell 中直接做):
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' only run this if there is a style to apply
If Not CellStyle.Cell Is Nothing Then
With CellStyle
.Cell.Value = .Text
.Cell.Font.Size = .Size
.Cell.Font.Color = RGB(255, 100, 0)

Set .Cell = Nothing ' reset so it does not run again with every cell selection change
End With
End If
End Sub
直接在 changeCell中更改某些单元格属性的原因不起作用是因为超链接的作用与 Evaluate(changeCell) 相同.如果您检查它是否可以更改颜色,但例如。不是 Evaluate 的字体大小.因此需要解决方法。
enter image description here

关于excel - 为什么我不能使用由 =hyperlink() 公式触发的 VBA 函数更改单元格中的字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68112295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com