簡體   English   中英

Excel VBA 宏來格式化單元格

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM