Excel VBA 格式化单元格的宏

Excel VBA macro to format cells

我写了一个包含重复代码的 Excel 子代码,其中活动范围以特定方式格式化,但我认为不可能将这些情况组合成一个循环。 是否可以编写一个单独的 sub/function 来获取输入范围、对其进行格式化并输出该格式化范围,就像 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。 return 范围没有任何意义,因为它与您作为 InputRange 发送的范围相同。因此,例如,如果您致电 ColorAndMerge SeperateRange 在你的主程序中你不需要 ColorAndMerge 到 return 任何东西,因为它只会 return 与你已经知道的 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

另请注意,调用 procedures/subs 时必须 不带 括号,而调用函数时 括号:

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!