excel vba总结dynamic最后一栏

macros观目的:

  • macros循环通过一个csv文件的文件夹
  • 对最后2列求和,并将结果放在第1行的相邻两个单元格中

例如: file1.csv最后2列是K和L,所以列L的总和放在单元格M1中,列K的总和放在单元格N1中。 file2.csv可能有不同数量的列,所以一直试图为这4个要求设置variables。

我能find的最接近的例子是: 使用最后一列作为范围(F:LastColumn)

我遇到的问题是我已经把file1.csv中的最后一列设置为一个variables,但是当总结这个variables时不允许使用这个语法:

Range("M1") = Application.WorksheetFunction.Sum(Columns("lastColLetter:lastColLetter")) 

不知道如何解决上面的语法。 下面的完整代码:

  Sub Macro1_Measure1_2() ' ' Dim my_Filename As String Dim lastCol As Long Dim lastColLetter As String '-------------------------------------------- Workbooks.Open Filename:="file1.csv" ' ' variable1: to store last column ' https://stackoverflow.com/questions/16941083/use-last-column-for-a-rangeflastcolumn 'lastCol = 12 'manual test lastCol = Cells(1, Columns.Count).End(xlToLeft).Column 'option-2 Debug.Print lastCol lastColLetter = GetColumnLetter(lastCol) ' check the range we've set Debug.Print lastColLetter ' variable2: to store 2nd last column ' logic = lastCol -1 col 'Range("M1") = Application.WorksheetFunction.Sum(Columns("L:L")) 'option-1 works but needs to be dynamic Range("M1") = Application.WorksheetFunction.Sum(Columns("lastColLetter:lastColLetter")) 'option-2 End Sub Function GetColumnLetter(colNum As Long) As String Dim vArr vArr = Split(Cells(1, colNum).Address(True, False), "$") GetColumnLetter = vArr(0) End Function ''''''''''' ''' END ''' '''''''''''