excel - 组合单元格的 Excel VBA 问题
问题描述
我正在编写一个 Excel VBA 程序来生成文本。我正在使用 IF 语句来确定某个特定文本是否在单元格中,并根据该文本连接一个字符串。
我对组合单元格有疑问:
IF Cells(1,1) Like "A" and Cells(1,2) Like "---" Then
concatenate something
end if
以上作品
IF Cells(2,1) Like "B" and Cells(2,2) Like "---" Then
concatenate something
end if
这不起作用,因为根据 MsgBox (Cells(2, 2).Value) 而不是“---”,Cell(2,2) 是空的。
是否可以让代码正常工作,而无需再次拆分单元格?
我想逐行连接文本,VBA代码应该将“B”右侧的单元格值识别为“---”。
解决方案
Cells(1,1).Value
是“A”。 Cells(1,2).Value
是 ” - -”。
Cells(2,1).Value
是空的。 Cells(3,2).Value
是空的。
Cells(3,1).Value
为B”。 Cells(3,2).Value
是空的。
仅仅因为您合并了上面的单元格,并不会改变单元格在第 3 行中。只有合并范围中的左上角单元格有值。(虽然,有办法 解决这个问题。)
您可以使用Range.MergeCells
.检查单元格是否合并。您可以使用获得合并单元格的值Range.MergeArea
例如:
Cells(1,1).MergeArea.Cells(1,1)
是“A”。 Cells(2,2).MergeArea.Cells(1,1)
是 ” - -”。 Cells(1,1).MergeCells
是True
。
Cells(2,1).MergeArea.Cells(1,1)
是“A”。 Cells(2,2).MergeArea.Cells(1,1)
是 ” - -”。 Cells(2,1).MergeCells
是True
。
Cells(3,1).MergeArea.Cells(1,1)
为B”。 Cells(3,2).MergeArea.Cells(1,1)
是 ” - -”。 Cells(3,1).MergeCells
是False
。
如果您使用循环遍历单元格,请考虑使用 aWhile
或Do
代替 a For
,因为您可以为每次迭代增加不同的数字:
Dim rowCurrent AS Long
rowCurrent = 1
While Cells(rowCurrent,1).Value <> ""
If Cells(rowCurrent,2).MergeArea.Cells(1,1).Value = "---" Then
Select Case Cells(rowCurrent,1).MergeArea.Cells(1,1).Value
Case "A"
'concatenate something
Case "B"
'concatenate something else
Case "C"
'concatenate a third thing
Case Else
'throw an error?
End Select
End If
'Skip the rest of the merged cell
rowCurrent = rowCurrent + Cells(rowCurrent,1).MergeArea.Rows.Count
Wend
推荐阅读
- angular2-nativescript - 如何在 NativeScript 中使用倒数计时器?
- powershell - 如何在 PowerShell 中为多个文件运行命令
- java - 在java中将Json数组转换为Map
- python - AttributeError at /admin/ 'tuple' object has no attribute 'regex' while upgrading django version from 1.5 to 1.8
- sql - 如何按纬度和经度(Postgis)从表中选择多边形
- ocr - 带有数字表的 Tesseract OCR
- decimal - 如何将前导零的数字解释为十进制?
- java - 如何确定哪些矩形与给定矩形有最大重叠?
- python - 如何修复 imshow() 显示灰色图像
- llvm - llvm 加载大型结构