宏目的:
示例: file1.csv最后2列是K和L,因此列L的总和放在单元格M1中,列K的总和放在单元格N1中。 file2.csv可能有不同的列数,因此一直试图为这4个要求设置变量。
我能找到的最接近的例子是: Use Last Column for a Range(F:LastColumn)
我遇到的问题是我已经将file1.csv中的最后一列设置为变量,但在对此变量求和时不允许语法:
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 '''
'''''''''''