Vba只计算28行从D列开始到最后一列的总和写到改行的最后一列的空白中
时间: 2024-05-25 11:19:28 浏览: 25
以下是一个示例代码,可以实现您想要的功能:
Sub SumColumns()
Dim lastRow As Long
Dim lastCol As Long
Dim i As Long
Dim j As Long
Dim sum As Double
lastRow = 28
lastCol = ActiveSheet.Cells(lastRow, Columns.Count).End(xlToLeft).Column
For i = 1 To lastRow
sum = 0
For j = 4 To lastCol
sum = sum + Cells(i, j).Value
Next j
Cells(i, lastCol + 1).Value = sum
Next i
End Sub
解释:
- 首先定义了变量lastRow和lastCol,分别表示最后一行和最后一列的行号和列号。
- 然后使用ActiveSheet.Cells方法找到最后一列的列号。
- 接着使用两个嵌套的for循环,分别遍历28行中从第4列到最后一列的单元格,并将它们的值加起来。
- 最后将计算结果写入到每行最后一列的空白单元格中。
相关问题
Vba找到数据最后一列移动到空白列,清空这一列
以下是一个示例VBA代码,可用于找到数据最后一列并将其移动到下一个空白列,并清空该列:
Sub MoveAndClearLastColumn()
Dim lastCol As Integer
Dim nextCol As Integer
Dim lastRow As Integer
'找到最后一列
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
'找到下一个空白列
nextCol = lastCol + 1
While Cells(1, nextCol) <> ""
nextCol = nextCol + 1
Wend
'将最后一列移动到下一个空白列
Columns(lastCol).Cut Destination:=Columns(nextCol)
'清空最后一列
lastRow = Cells(Rows.Count, lastCol).End(xlUp).Row
Range(Cells(1, lastCol), Cells(lastRow, lastCol)).ClearContents
End Sub
请注意,此代码假定您的数据不包含任何合并单元格。如果您的数据包含合并单元格,则此代码可能会引起问题。
写一个VBA按列区分,逐行相加得到的和写到最后一行
你可以使用以下的VBA代码实现你的需求:
```
Sub SumByColumn()
Dim lastRow As Long
Dim lastCol As Long
Dim row As Long
Dim col As Long
Dim sum As Double
lastRow = Cells(Rows.Count, 1).End(xlUp).Row '获取最后一行的行号
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column '获取最后一列的列号
For col = 2 To lastCol '从第2列开始遍历每一列
sum = 0 '初始化每一列的和为0
For row = 1 To lastRow '遍历当前列的每一行
sum = sum + Cells(row, col).Value '累加当前行的值
Next row
Cells(lastRow + 1, col).Value = sum '将当前列的和写入最后一行
Next col
End Sub
```
上述代码会按列区分,逐行相加得到的和,并将结果写入最后一行。你只需要将代码复制到VBA编辑器中,然后运行即可。请注意,你需要在Excel表格中打开VBA编辑器才能运行这段代码。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)