excel - VBA code in command button doesn't work on button click -
i'm don't know vba , i'm doing out of necessity forgive me. t-sql.
i found following code in article take data excel sheet , output txt file used run through scribe. far;
- i've placed command button on sheet
- i've right clicked view code
- i pasted code article vba editor , adapted parts of needs (the file path basically)
when run code editor performs perfectly.
when close editor , click button on sheet runs resulting text file appropriate number of empty strings in text file. it's can see number of rows have data not actual data in cells.
have missed obvious? can't see more in article (which isn't written complete novices have say) solve problem!
sub commandbutton1_click() dim filepath string dim rng range dim celldata string dim lastcol long dim lastrow long lastcol = activesheet.usedrange.specialcells(xlcelltypelastcell).column lastrow = activesheet.usedrange.specialcells(xlcelltypelastcell).row set rng = worksheets("discount template").range("b3") filepath = "\\server2012\it dept\accesssupplychain\product discount uploads\" & rng.value & "_" & format(now(), "yyyymmdd hhmmss") & ".txt" open filepath output #2 = 1 lastrow j = 1 lastcol if j = lastcol celldata = celldata + trim(activecell(i, j).value) else celldata = celldata + trim(activecell(i, j).value) + "," end if next j print #2, celldata celldata = "" next close #2 msgbox ("done") end sub
the issue use of activecell
not obliged a1 cell!
so want change activecell(i, j)
cells(i, j)
but propose following refactoring of code:
option explicit private sub commandbutton1_click() dim filepath string dim rng range dim irow long set rng = worksheets("discount template").range("b3") filepath = "\\server2012\it dept\accesssupplychain\product discount uploads\" & rng.value & "_" & format(now(), "yyyymmdd hhmmss") & ".txt" open filepath output #2 usedrange '<--| reference active sheet used range irow = 1 .rows.count '<--| loop through rows print #2, join(application.transpose(application.transpose(.rows(irow))), ",") '<--| print whole current row in 1 shot next end close #2 msgbox ("done") end sub
Comments
Post a Comment