Ken.T
Ken.T

Reputation: 3

Edit R-script using Excel VBA

I would like to creat a excel macro by using vba, which can edit R-scripts.

Let's call this R script starter.R and its working directory is C:/Documents. The Code I want to change is "run=3000". I want to change it to "run=2000".

Firstly I want to open the R-script by using the following code:

Sub ReplaceString()
Dim filename as string
Dim location as String
location="C:\Users\Ken\Documents"
filename="C:\Users\Ken\Documents\start.R"
'Open filename

Then I want to replace the string "run=3000" to "run=2000".

'Replace("run=3000","run=2000")
end sub

Can somebody help me?

Upvotes: 0

Views: 477

Answers (1)

Jagadish Dabbiru
Jagadish Dabbiru

Reputation: 940

Try this Code, It might help you

  Sub ReplaceString()
  Set fs = CreateObject("Scripting.FileSystemObject")
  Set Ofs =fs.OpenTextFile("C:\Users\Ken\Documents\Start.R",1,False) 
  Txt = Ofs.ReadAll
  StrToFnd = "run" & "=" & "3000"
  StrToRplc = "run" & "=" &"2000"          

  Temp=Replace(Txt,StrToFnd,StrToRplc)
  Ofs.Close
  Set Ofs = Nothing
  Set Ofs=fs.OpenTextFile("C:\Users\Ken\Documents\Start.R",2,False) 
  Ofs.WriteLine(Temp)
  Ofs.Close
  End Sub

Upvotes: 1

Related Questions