Excel VBA – 将parameter passing给一个函数
我试图创build一个Excel函数,该函数将以我要求的任何forms加粗所传达的任何范围。 不幸的是,我只是在正确传递variables并获得这个结果方面取得了部分成功。 当然,没有人喜欢一个部分,所以有人请让我知道我错过了什么。
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
请帮忙。
你的函数参数的括号引起了这个问题。 他们强制封装的值在作为函数parameter passing之前进行评估,传递一个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")))
为了获得更多关于这个问题的细节,你需要删除这个语句
On Error Resume Next
(又名On Error Hide All Bugs
)
我删除后,我能够确定问题
-
该函数(应该是一个Sub,因为它不会返回一个值)需要一个Range对象:
Text_bold(
x As Range)
-
Text_bold ([b1].Address)
用圆括号不正确地调用它,它试图发送一个string作为参数,而不是范围 -
你所有的函数调用都应该没有括号
尝试这个:
Sub Macro1() 'Create & reset testing area. Range("A1:C6").Value = "A" Range("A1:C6").Font.Bold = False [b2].Select Text_bold [a1] Text_bold Cells(2, 1) Text_bold [b1] Text_bold Selection Text_bold Range("B3") Text_bold Range("B4:C4") Text_bold Application.Union(Range("B5:C5"), Range("B6:C6")) 'A sub cannot return a value, a function can but it doesn't have to 'To return a value from the Text_bold function Dim functionResponse As Boolean functionResponse = Text_bold([B3]) '<- THIS is where you need to use brackets MsgBox "Text in Cell [B3] is bold: " & functionResponse End Sub Function Text_bold(x As Range) As Boolean x.Font.Bold = True Text_bold = (x.Font.Bold = True) 'assign the return value to the function name End Function