vba - Trying to write text to a file error '5' -


i trying take code, go through , delete tags , write new document testfile.txt. reason getting error line 5: set ts = f.openastextstream(forwriting, tristateusedefault) , getting error invalid procedure. here code:

sub elizabethwhite() set fs = createobject("scripting.filesystemobject") fs.createtextfile "testfile.txt" set f = fs.getfile("testfile.txt") set ts = f.openastextstream(forwriting, tristateusedefault)  textline = "" while f.opentextstream(forwriting, tristateusedefault).atendofstream <> true textline = textline & f.opentextstream(forwriting, tristateusedefault).readline & "<br>"  count = 0 pone = 1 while instr(textline, "<img") <> 0 count = count + 1 pone = instr(pone, textline, "<img")  while instr(pone, textline, ">") = 0 & ts.atendofstream <> true ptwo = instr(pone, textline, ">") loop  if 0 < count < 10 textline = left(textline, pone - 1) & "{{image00" & count & ".jpg}}" & right(textline, ptwo + 1) elseif 9 < count < 100 textline = left(textline, pone - 1) & "{{image0" & count & "}}.jpg" & right(textline, ptwo + 1) end if loop loop ts.write textline ts.close  end sub 

properly declaring variables, , using option explict identify problem. not tomention, these habits develop , write better code. enable script assist feature, comes in handy.

the problem have not enabled reference ms scripting runtime library and because of this, forreading , tristateusedefault being interpreted compiler variables , variables no values, passing invalid parameters openastextstream method.

option explicit have helped identified error:

option explicit helps identify errors uninitialized variables

if add reference microsoft scripting runtime, code work as-is, still urge declare variables type, , use option explicit. both save lot of trouble in future :)

enter image description here

sub elizabethwhite()      dim fs new scripting.filesystemobject     dim f scripting.file     dim ts scripting.textstream       fs.createtextfile "testfile.txt"     set f = fs.getfile("testfile.txt")      set ts = f.openastextstream(forwriting, tristateusedefault)      ts.writeline "hello!"      '     '### rest of code goes here... remember declare other variables :)     '      set ts = nothing     set f = nothing     set fs = nothing  end sub 

see (documentation openastextstream method):

http://msdn.microsoft.com/en-us/library/aa265341(v=vs.60).aspx


Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -