vba - Looping through Excel Cells and writing them to Word -
i using macro in excel loop through cells , write data template in word. worked fine until wanted add more cells grab data from. still works fine except once variable have name "j" gets value of 25, error saying "run-time error '5941': requested member of collection not exist."
i've played around using different rows , columns , every combination works. when "j
" reaches 25 error occur. failing when reaches wrd.activedocument.tables(1).rows(j)
... line.
sub label_exceltoword_single() 'variable stores file path 'word template dim strpath string strpath = cells(28, 8) 'opens microsoft word edit template call openword set wrd = getobject(, "word.application") wrd.visible = true wrd.activate wrd.activedocument.close savechanges:=false wrd.documents.open strpath 'variables used loop data manipulation dim k integer dim j integer k = 1 j = 1 'primary loop responsible exporting excel 'data word template col = 1 3 row = 3 32 wrd.activedocument.tables(1).rows(j).cells(((row - 3) mod 7) + k).range.text = cells(row, col) & vbcrlf & cells(row, col) if k = 7 k = 0 j = j + 2 end if if col = 3 if row = 32 'when reach last cell containing data exit routine exit sub end if end if k = k + 1 next next end sub
looks table might not have enough rows. if so, brute-force way add rows need them:
... col = 1 3 row = 3 32 ' vvv new lines vvv while wrd.activedocument.tables(1).rows.count < j wrd.activedocument.tables(1).rows.add loop ' ^^^ new lines ^^^ ...
i recommend renaming j
, k
, row
, , col
more descriptive names. have excel row/column indices , word-table row/column indices, , it's easy them confused unless names clear.
(note: yes, above code slow, clunky, unoptimized, yadda yadda. op. :) )
Comments
Post a Comment