简体   繁体   English

VBA-单元格颜色

[英]VBA - cells color

What is wrong with this code? 此代码有什么问题? I get an "ARG!" 我得到一个“ ARG!” error 错误

Public Function nr_kolor(kom As Range)  
  For Each komorka In kom
    wartosc = komorka.Font.Color
    wiersz = komorka.Row
    kolumna = komorka.Column + 3
    nr_kolor = wartosc
  Next komorka
  activesheet.Cells(wiersz, kolumna).Select
  Selection.Interior.Color = wartosc  
End Function

There are a lot of things you are doing wrong. 您做错了很多事情。

  • You have failed to declare your variables. 您未能声明变量。
  • You need to use a Sub() not Function(). 您需要使用Sub()而不是Function()。 As a rule, functions are not allowed to alter the worksheet in any way, just manipulate and return values. 通常,不允许函数以任何方式更改工作表,而只能操作和返回值。
  • Your loop has errors - if you wish to do things to more than one cell than all your instructions need to be within the loop. 循环中有错误-如果您希望对一个以上的单元执行操作,则所有指令都不需要包含在循环中。 Right now it only colors 1 cell (3 columns right of the LAST cell in your range). 现在,它只为1个单元格上色(您范围中最后一个单元格右边的3列)。
  • You are returning the function before the function is over. 您要在函数结束之前返回函数。

I think what you are trying to do (there was no explanation) is take a range of cells, and apply the same interior color to the cells three columns over. 我认为您要尝试做的事(没有任何解释)是采用一系列单元格,并将相同的内部颜色应用于三列以上的单元格。 Here is a more effecient way to do this. 这是一种更有效的方法。 I have purposly kept the logic simple. 我的逻辑很简单。

Sub ColorCells()

Dim cell As Range

For Each cell In Range("A1:A10")
    cell.Offset(, 3).Interior.Color = cell.Interior.Color
Next

End Sub

How it works : You create a variable cell as a range, this will represent each cell in the range you supply. 工作原理 :创建一个变量单元格作为范围,它将代表您提供的范围内的每个单元格。 For each cell in the range, you want to apply the same interior color to the cell OFFSET 3 columns to the right. 对于该范围中的每个单元格,您希望将相同的内部颜色应用于右侧的单元格“偏移3”列。

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

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