Excel VBA 方法和函数(Excel 宏)概述
由于您想更改单元格,我不相信您可以使用公式(即使不是用户定义的公式)。因此,我为您的问题编写了一个 excel vba 宏。
- FirstRows():是起点。它循环超过 10 行并调用其他方法
- CheckEmptyCellValues(curRow):此方法检查 tab2 中的空单元格(excel 中的工作表 2)
- MergeCells(curRow) 将当前行作为一个数字(从 1 到最大行数的任何整数)并合并工作表 1(excel 中的第一张工作表)上第 1 列到第 4 列的单元格
4 列 10 行的完整工作演示测试
Sub FirstRows()
Sheets(1).Select
For curRow = 2 To 11
Merge = CheckEmptyCellValues(curRow)
If Merge = 4 Then
MergeCells (curRow)
cellValue = Sheets(2).Cells(curRow, 4).Value
Sheets(1).Cells(curRow, 1).Value = cellValue
End If
Next
End Sub
Sub MergeCells(curRow)
Sheets(1).Select
Range(Cells(curRow, 1), Cells(curRow, 4)).MergeCells = True
End Sub
Function CheckEmptyCellValues(curRow)
Merge = 0
Sheets(2).Select
For i = 1 To 4
If Len(Cells(curRow, i).Value) > 0 Then
Merge = Merge + 1
End If
Next
CheckEmptyCellValues = Merge
End Function
您可以在下面看到结果。表 2 中的值已复制到表 1(第二张图像)。在表 1 中,如果在第一个图像(表 2)中每个单元格(从 a 列到 d 列),则合并一行中的单元格(在第 2 行中,从单元格 A2 到单元格 D2(A2-D2 现在只是一个单元格)连续有一个值。
修改代码中的错误
修改后的代码中有几处是不可能的或可能导致错误理解的地方
Function CheckEmptyCellValues(curColumn)
Merge = 0
Sheets(2).Select
For i = A To d
If Len(Cells(curColumn, 11).Value) > 0 Then
Merge = Merge + 1
End If
Next
CheckEmptyCellValues = Merge
End Function
-
For i = A To d 行是不可能的。如果你想使用循环,你必须使用数字:For i = 1 To 4 这将在For 和Next之间重复代码 4 次,从 1 开始
-
Cells(curColumn, 11).Value 这一行在技术上是正确的,但具有误导性。 Excel 使用( 之后的第一个值作为行索引,使用第二个值作为列索引。两个值都必须是一个数字: Cells(4,2).Value 从第 4 个开始返回 Cell 值。行和第二列(在 Excel Gui 单元格 B4 中)
尝试将此行 For i = A To d 更改为此 For i = 1 To 4 并查看是否返回所需的结果。
错误第 2 部分
在您的其他修改中,您有一些相同的错误:
- 循环
For curColumn = A to d 需要数字而不是字母(除非 A 和 d 是一个用数字填充的变量,但根据您的代码示例,情况并非如此
-
cellValue = Sheets(2).Cells(curColumn, d).Value 行有同样的错误,如果 d 只是字母 d 而不是像 d = 4 这样的东西,那么你不能在循环中使用它。
这是您评论中的代码:
Sub FirstRows()
Sheets(1).Select
For curColumn = A To d
Merge = CheckEmptyCellValues(curColumn)
If Merge = d Then
MergeCells(curColumn)
cellValue = Sheets(2).Cells(curColumn, d).Value
Sheets(1).Cells(curColumn, d).Value = cellValue
End If
Next
End
Sub Sub MergeCells(curColumn)
Sheets(1).Select
Range(Cells(curColumn, 1), Cells(curColumn, d)).MergeCells = True
End Sub
小心它没有运行。