Excel VBA:函数如何返回带有各种彩色字符的字符串?

时间:2014-07-29 18:33:44

标签: string vba colors

我在下面的代码中应该生成类似于的字符串 "XXXXX|XXXXX|XXXXX|XXXXX|XXXXX|XXXXX"
这代表5个工作日,每个工作日为6周,用于安排我的建筑 我也希望前几个X是黑色的,其余的是红色。例如,我们可能会在第二周完成,我希望前7个X是黑色的,其余的都是红色的。

我的代码生成此字符串就好了。但是,我无法弄清楚颜色是否会发生。我无法弄清楚如何为从函数返回的实际字符串着色。所以我尝试添加一个自我单元格引用(TargetCell参数),这样一旦我构建了字符串,我就可以为结果着色。

在我的电子表格单元格D3中,我有公式
=BuildColorString(A3, A4, A5, C2, C3, D3, B41:B45)
不要担心前5个参数或最后一个参数。专注于第6个参数,即对D3的自我引用。

无论如何,如果我将第5个参数设置为完全不同的单元格,则该单元格中的文本会正确显示。但是,如果我尝试为我生成的结果着色,它就不起作用。

我意识到我这里有鸡蛋问题。我无法弄清楚如何克服它。

我也尝试从着色中分割字符串生成。我把颜色放在我按下的按钮后面。它不起作用。我似乎无法为函数的字符串构建的结果着色。

以下是我的代码:

Function BuildColorString(BeginDate As Date, EndDate As Date, Holidays As Integer, AsOfDate As Date, HolidaysPassed As Integer, TargetCell As Range, rColors As Range)
Dim iDayCount As Integer
Dim iPosition As Integer
Dim iColor As Integer
Dim WIPDate As Date
Dim iWeekDay As Integer

' BUILD STRING
BuildColorString = ""
WIPDate = BeginDate
While WIPDate <= EndDate
    iWeekDay = Weekday(WIPDate)
    If (iWeekDay = 1) Then
        'Sunday
    Else
        If (iWeekDay = 7) Then
            'Saturday
            If (WIPDate <> BeginDate) Then
                BuildColorString = BuildColorString & "|"
            End If
        Else
            'Weekday
            BuildColorString = BuildColorString & "X"
        End If
    End If
    WIPDate = WIPDate + 1
Wend

' COLORIZE STRING
WIPDate = BeginDate
iDayCount = 1
iPosition = 1
While WIPDate <= EndDate
    iWeekDay = Weekday(WIPDate)
    If (iWeekDay = 1) Then
        'Sunday
    Else
        If (iWeekDay = 7) Then
            'Saturday
            If (WIPDate <> BeginDate) Then
                iPosition = iPosition + 1
            End If
        Else
            'Weekday
            If (iPosition <= 5) Then
                ' BLACK, Prior Completed
                iColor = rColors(1, 1).Characters(1, 1).Font.ColorIndex
            Else
                ' GREEN, Recent Completed
                iColor = rColors(3, 1).Characters(1, 1).Font.ColorIndex
            End If

            TargetCell(1, 1).Characters(iPosition, 1).Font.ColorIndex = iColor

            ' BuildColorString.Characters(iPosition, 1).Font.ColorIndex = vbRed 'rColor.Font.ColorIndex
            iDayCount = iDayCount + 1
            iPosition = iPosition + 1
        End If
    End If
    WIPDate = WIPDate + 1
Wend


End Function

0 个答案:

没有答案