简体   繁体   English

excel vba 子程序调用失败

[英]excel vba subroutine call fails

I have the following problem.我有以下问题。 I want to call a soubroutine for changing the background color for a cell range.我想调用一个子程序来更改单元格范围的背景颜色。 The cell range is calculated with cells(1,1) and then the address is calculated to receive A1.用cells(1,1)计算单元格范围,然后计算地址以接收A1。

Before the subroutine is called I get the addresses for my cells like this:在调用子程序之前,我得到了单元格的地址,如下所示:

Range1 = cells(4, 4).Address(RowAbsolute:=False, ColumnAbsolute:=False)
Range2 = cells(4, CellAmount - 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

I thought I need this because the subroutine is declared like this:我想我需要这个,因为子程序是这样声明的:

Sub SetBGLightGrey(cells As String)

    range(cells).Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 15921906
        .TintAndShade = 0
       .PatternTintAndShade = 0
    End With

End Sub

Range 1 and Range 2 are strings and I concat it to a range declaration:范围 1 和范围 2 是字符串,我将其连接到范围声明:

RangeArea = """" & Range1 & ":" & Range2 & """"

When I call my subroutine like this:当我这样调用我的子程序时:

Call SetBGLightGrey(RangeArea)

I get the following error-message:我收到以下错误消息:

"Run-time error '1004': Method 'Range' of object '_Global' failed. I don't understand it because if I call the subroutine with the correct cell values: “运行时错误'1004':object'_Global'的方法'范围'失败。我不明白,因为如果我用正确的单元格值调用子例程:

Call SetBGLightGrey("D4:K4")

it works.有用。 It is string and of the same value.它是字符串并且具有相同的值。 This simply cannot be can it?这根本不可能可以吗?

You do not need quotes around RangeArea.您不需要 RangeArea 周围的引号。

RangeArea = Range1 & ":" & Range2

But then, why would you want to pass ranges around as strings and then convert them back to ranges?但是,为什么要将范围作为字符串传递,然后将它们转换回范围呢? Pass the range objects all the time.始终传递范围对象。

Sub SetBGLightGrey(byval cells as range)
  With cells.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 15921906
    .TintAndShade = 0
    .PatternTintAndShade = 0
  End With
End Sub 

SetBGLightGrey range(cells(4, 4), cells(4, CellAmount - 1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM