gpt4 book ai didi

vba - Excel VBA - 将参数传递给函数

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

我尝试创建一个 Excel 函数,该函数将以我要求的任何形式加粗我告诉它的任何范围。不幸的是,我在正确传递变量并获得这个结果方面只取得了部分成功。当然,没有人喜欢部分内容,所以有人可以让我知道我错过了什么。

Sub Macro1()
On Error Resume Next

'Create & reset testing area.
Range("A1:C6").value = "A"
Range("A1:C6").Font.Bold = False
[b2].Select

'The two lines below call the function perfectly and the cells are bolded without issue
Text_bold ([a1])
Text_bold (Cells(2, 1))

'However, the party stops there as the following code errors out.
Text_bold ([b1].Address)
Text_bold (Selection)
Text_bold (Range("B3"))
'Similarly, the below fails as well...
Text_bold (Range("B4:C4"))
'And even less surprising, the following also refuses to assist in the endeavor...
Text_bold (Application.Union(Range("B5:C5"), Range("B6:C6")))
End Sub

Function Text_bold(x As Range)
'MsgBox VarType(x)
x.Font.Bold = True
End Function

请帮忙。

最佳答案

函数参数周围的括号导致了问题。他们强制在将封闭的值作为函数参数传递之前对其进行评估,传递 Range.Value 而不是 Range 对象。

Sub Macro1()
On Error Resume Next

'Create & reset testing area.
Range("A1:C6").Value = "A"
Range("A1:C6").Font.Bold = False
[b2].Select

'The two lines below call the function perfectly and the cells are bolded without issue
Text_bold [a1]
Text_bold Cells(2, 1)

'However, the party stops there as the following code errors out.
Text_bold Range([C1].Address)
Text_bold Selection.Range
Text_bold Range("B3")
'Similarly, the below fails as well...
Text_bold Range("B4:C4")
'And even less surprising, the following also refuses to assist in the endeavor...
Text_bold Application.Union(Range("B5:C5"), Range("B6:C6"))
MsgBox "OK"
End Sub

如果您确实想使用括号,请在函数前面加上 Call 语句。

Call Text_bold(Application.Union(Range("B5:C5"), Range("B6:C6")))

关于vba - Excel VBA - 将参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44712909/

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