我试图在VBA中编写一个函数,该函数允许我连接单元格并在元素之间添加“,”。此功能的另一方面是,我只想连接与所选范围中的第一个填充颜色和字体颜色相同的单元格。(我的电子表格在具有不同颜色和字体颜色的单元格中具有标签列表)。如果在网上找到了可以满足条件的代码,那么您会感到惊奇。但是,当我尝试添加它们时,它返回值错误。这是我的功能:
Function Concat(rng As Range) As String
Dim rngCell As Range
Dim strResult As String
Dim bcolor As Long
Dim fcolor As Long
bcolor = rng.Cells(1, 1).Interior.ColorIndex
fcolor = rng.Cells(1, 1).Font.ColorIndex
For Each rngCell In rng
If rngCell.Value <> "" And rngCell.Interior.ColorIndex = bcolor And rngCell.Font.ColorIndex = fcolor Then
strResult = strResult & "," & rngCell.Value
End If
Next rngCell
If rngCell.Value <> "" And rngCell.Interior.ColorIndex = rng.Cells(1, 1).Interior.ColorIndex And rngCell.Font.ColorIndex = rng.Cells(1, 1).Font.ColorIndex Then
strResult = Mid(strResult, Len(",") + 1)
End If
Concat = strResult
End Function
我刚接触VBA(今天下午开始),所以我添加bcolor和fcolor的原因是为了调试。实际上,我认为VBA中有些我不了解的基本知识,因为即使以下函数也不会返回任何值:
Function Concat(rng As Range) As Long 'Replace "Long" by "String" after debug is over
Dim rngCell As Range
Dim strResult As String
Dim bcolor As Long
Dim fcolor As Long
bcolor = rng.Cells(1, 1).Interior.ColorIndex
fcolor = rng.Cells(1, 1).Font.ColorIndex
For Each rngCell In rng
If rngCell.Value <> "" And rngCell.Interior.ColorIndex = bcolor And rngCell.Font.ColorIndex = fcolor Then
strResult = strResult & "," & rngCell.Value
End If
Next rngCell
If rngCell.Value <> "" And rngCell.Interior.ColorIndex = rng.Cells(1, 1).Interior.ColorIndex And rngCell.Font.ColorIndex = rng.Cells(1, 1).Font.ColorIndex Then
strResult = Mid(strResult, Len(",") + 1)
End If
Concat = bcolor
End Function
确实让我感到烦恼的是,此函数在执行以下操作时不会返回单元格的颜色:
Function color1(rng As Range) As Long
color1 = rng.Cells(1, 1).Font.ColorIndex
End Function
我知道这里有些VBA编码我不了解的基本知识。但是我不知道该怎么办。如果您发现问题出在哪里,我将更正并解释我的错误是什么。谢谢!泽维尔
不确定代码的最后部分是否执行了您想要的操作。另外,您不能在rngCell
外部使用For Each rngCell In rng
。
语句的内部仅删除字符串的第一个字符。(Mid()
从提供参数的位置的字符处开始截断字符串,如果要提供第二个数字,它将设置子字符串将包含的字符数;Len()
将返回提供的字符串的长度)。
因此,这strResult = Mid(strResult, Len(",") + 1)
几乎意味着存储原始字符串的一个字符串,但从字符2(1 + 1)开始。
尝试这个!
Function Concat(rng As Range) As String
Dim rngCell As Range
Dim strResult As String
Dim bcolor As Long
Dim fcolor As Long
bcolor = rng.Cells(1, 1).Interior.ColorIndex
fcolor = rng.Cells(1, 1).Font.ColorIndex
For Each rngCell In rng
If rngCell.Value <> "" And rngCell.Interior.ColorIndex = bcolor And rngCell.Font.ColorIndex = fcolor Then
If strResult = "" Then
strResult = rngCell.Value
Else
strResult = strResult & ", " & rngCell.Value
End If
End If
Next rngCell
'this probably doesn't do what you want, so I commented it out.
'If rngCell.Value <> "" And rngCell.Interior.ColorIndex = rng.Cells(1, 1).Interior.ColorIndex And rngCell.Font.ColorIndex = rng.Cells(1, 1).Font.ColorIndex Then
' strResult = Mid(strResult, Len(",") + 1)
'End If
Concat = strResult
End Function
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句