VBA连接和总和

我需要编写一个可以在SHEET2上连接数字的macros(可能看起来像这样):

ABCD 1 4 3 2 1 2 5 6 3 7 8 0 

像这样(4321 + 56 + 780 = 5157)拿出SHEET1的总和:

  A 1 5157 

到目前为止,我没有写出任何macros,所以任何帮助将不胜感激!

你知道你可以做到这一点没有macros,对不对?

 =SUMPRODUCT((A1:A3&B1:B3&C1:C3&D1:D3)+0) 

这应该正是你所要求的。 一个Excel VBA脚本连接在Sheet2每一行中的所有值(永远),将行总计加在一起,并将它们显示在Sheet1 。 我已经用你的数据集testing过了,它能正常工作。

 Sub concatSum() Dim row As Integer Dim rowVal As String Dim col As Integer Dim colVal As String row = 1 col = 1 totalVal = 0 rowVal = "" With Worksheets("Sheet2") Do While Len(.Cells(row, 1).Value) > 0 colVal = .Cells(row, col).Value Do While Len(colVal) > 0 rowVal = rowVal & colVal col = col + 1 colVal = .Cells(row, col).Value Loop col = 1 row = row + 1 totalVal = totalVal + rowVal rowVal = "" Loop End With Worksheets("Sheet1").Cells(1, 1).Value = totalVal End Sub 

使用Ctrl + Shift + Enter:

 =SUM(CONCATENATE(A1:A3,B1:B3,C1:C3,D1:D3)*1) 

忽略错误:

 =SUM(IFERROR(CONCATENATE(B2:B4,C2:C4,D2:D4,E2:E4)*1,0)) 

不需要VBA ,使用:

 =VALUE(CONCATENATE(A1,B1,C1,D1))+VALUE(CONCATENATE(A2,B2,C2,D2))+VALUE(CONCATENATE(A3,B3,C3,D3)) 

并改变参考你喜欢的任何工作表。

在这里输入图像说明

 Sub concadinate_sum() Dim LstRow As Long Dim LstCol As Long, c As Variant Dim i As Long Dim j As Long Sheets("Sheet2").Activate LstRow = Sheets(2).Range("A1", Range("A1").End(xlDown).Address).Count For i = 1 To LstRow LstCol = Sheets(2).Range("A" & i, Range("A" & i).End(xlToRight).Address).Count For j = 0 To LstCol c = c & Sheets("Sheet2").Range("A" & i).Offset(0, j).Value Next j Sheets("Sheet1").Range("A1").Value = CInt(c) + CInt(Sheets("Sheet1").Range("A1").Value) c = "" Next i End Sub 

这里是VBA解决scheme

 Sub AddThem() Dim sh2 As Worksheet Set sh2 = ThisWorkbook.Worksheets("Sheet2") lr = sh2.Cells(sh2.Rows.Count, "A").End(xlUp).Row tot = 0 For i = 1 To lr tot = tot + (Cells(i, 1) & Cells(i, 2) & Cells(i, 3) & Cells(i, 4)) + 0 Next i Range("A1") = tot End Sub