[英]Excel VBA macro to format cells
我编写了一个包含重复代码的 Excel 子程序,其中活动范围以特定方式格式化,但我认为不可能将这些情况组合成一个循环。 是否可以编写一个单独的子/函数来获取输入范围,对其进行格式化并输出格式化的范围,就像 python 具有可定义的函数一样?
编辑:这是一些准系统伪代码
function Colour_and_Merge(Input Range)
Formatted range = *Input Range with text and background colour changed*
Colour_and_Merge = Formatted Range
end function
sub Main_Code()
for y = 1 to 3
if y <> 1
Colour_and_merge(Range(Cells(1,y),Cells(5,y)))
end if
Colour_and_Merge(Seperate_Range)
end sub
你会像下面那样做。
Option Explicit
Public Sub ColorAndMerge(ByVal InputRange As Range)
With InputRange
.Interior.Color = vbRed ' format range background red.
.Font.Bold = True ' format font bold
'what ever you like to do with that range put it here
End With
End Sub
Public Sub MainCode()
Dim y As Long
For y = 1 To 3
If y > 1 Then
ColorAndMerge Range(Cells(1, y), Cells(5, y)) 'make sure you specify in which workbook and worksheet your `Range` and `Cells` objects are!
End If
Next y
ColorAndMerge SeperateRange
End Sub
请注意,您不需要Function
而是Sub
。 返回范围没有任何意义,因为它与您作为InputRange
发送的范围相同。 因此,例如,如果您在主程序中调用ColorAndMerge SeperateRange
,则不需要ColorAndMerge
返回任何内容,因为它只会返回与您已经知道的SeperateRange
相同的内容。
因此,如果您的主要代码执行以下操作
Public Sub MainCode()
Dim SeperateRange As Range
Set SeperateRange = Range(Cells(1, y), Cells(5, y))
ColorAndMerge SeperateRange 'if you call the procedure
'here `SeperateRange` will be the formatted range. There is no need to return it in a function, the SeperateRange variable is just a reference to the real range in the worksheet that already got formatted by ColorAndMerge
End Sub
另请注意,调用过程/子程序必须不带括号,而调用带括号的函数:
ColorAndMergeSub SeperateRange ' correct
ColorAndMergeSub (SeperateRange) ' wrong! ... this syntax exists but does something entirely differnt than the first one
ReturnValue = ColorAndMergeFunction(SeperateRange) ' correct
ReturnValue = ColorAndMergeFunction SeperateRange ' wrong!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.