excel - Summing entire column and using input string in path -
sub value() dim fname string dim fld string set wb1 = thisworkbook set ws1 = wb1.worksheets("profit") set ws2 = wb1.worksheets("loss") ws1 lastrow = .cells(.rows.count, "b").end(xlup).row end = 1 lastrow **fld = ws1.cells.value(i, "b") fname = dir(fld & .cells(i, "c").value + "*.xls*")** set wb2 = workbooks.open(fld & fname, readonly:=true) wb1.worksheets("revenues").usedrange.clear wb2.worksheets("latest").usedrange.copy destination:=wb1.worksheets("revenues").range("a1") wb2.close savechanges:=false ws2 lastrow2 = .cells(.rows.count, "p").end(xlup).row end **ws1.cells(i, "e").value = excel.worksheetfunction.sum(ws2.range("p2" & lastrow2))** next end sub i facing small errors @ 2 places. first, file latest data opened using directory , file name provided string in b & c column, compiler doesn't take when use. secondly, when sum entire column gives 0 value always, don't know why. in short take file name , directory , place output number(sum column) besides it. sum(p:p) doesn't work.
fld = ws1.cells.value(i, "b") two issues this:
- it's
.cellsneeds cell reference, not.value - you're mixing
r1c1a1in cell reference
try way:
or:
fld = ws1.range("b" & i).value you're repeating error #2 in references you're using .cells()
additional error:
fname = dir(fld & .cells(i, "c").value + "*.xls*") in addition error #2, above, you're using + concatenation. vba uses &.
fname = dir(fld & .cells(i, 3).value & "*.xls*") note:
you may want consider putting error handling around set wb2 = workbooks.open(fld & fname, readonly:=true) line, since you're relying on user correctly enter path (you're assuming ends in \) , file name. slightest typo , .open() fail.
you may consider searching filesystemobject present user windows standard file dialog box can pick file want have opened. ensure (if cancel) or guaranteed valid path\filename since selected existing , didn't have type in.
Comments
Post a Comment