用于格式化单元格的 Excel VBA 宏

伊利斯

我编写了一个包含重复代码的 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
Pᴇʜ

你会像下面那样做。

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

请注意,您不需要 a Functionbut a 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!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Excel VBA 单击单元格以触发宏 - 不适用于合并的单元格

使用Excel宏重新格式化单元格内容

Excel宏刷新数据,然后格式化单元格

每个选定单元格的Excel VBA循环宏

VBA Excel宏-显示与列相关的单元格值

(Excel VBA)-从宏中的单元格文本绘制

VBA excel,在=“是”的单元格范围内运行宏

用于更改单元格值并运行模型的 VBA Excel 宏的索引值

Excel VBA,用于将单元格中的超链接公式链接到宏

如何使用excel vba在单元格中添加“₹”(格式化带有货币符号“₹”的单元格)

VBA Excel - 找到一个单元格并格式化下面的单元格

如何使用Excel宏更改(格式化)所选文本,而不是更改整个所选单元格

VBA:将访问权限导出到 Excel -> 选择所有单元格 -> 格式化表格

Excel 365 VBA宏

Excel宏非VBA

Excel VBA排序宏

Excel VBA宏

Excel将VBA宏复制单元格循环到新工作表

MS Excel 2007 VBA宏以插入三行单元格的值更改的位置

用双引号将单元格值引起来:Excel VBA宏

Excel VBA复制/粘贴宏:使用公式忽略单元格

当链接的单元格更改值时运行宏(Excel VBA)

如何使用vba宏从指定单元格开始计算excel中的行数

在单元格值更改时自动触发宏 |Excel|VBA|

Excel VBA宏复制单元格并粘贴到另一个

Excel 2010 VBA单击单元格触发器宏以显示值列表

使用Excel VBA宏对单列中的单元格范围进行排序

Excel VBA 宏仅查找并删除一些需要的单元格

VBA 和 Excel 我需要在单元格更改时运行宏