2

私はRubyを介して単語の自動化を行っていますが、比較的経験がありません。私は今自分のコードを機能させようとしていますが、このエラーに遭遇しています

NameError: undefined local variable or method `doc' for main:Object
    from (irb):148:in `create_table'
    from (irb):152
    from C:/Ruby192/bin/irb:12:in `<main>'

私がノックアップしたこのサンプルコードから得ているもの

#Get the correct packages
require 'win32ole'

#setting up the Word
word = WIN32OLE.new('Word.Application')
#Shows the word Application
word.Visible = true
#Setting doc to the active document
doc = word.Documents.Add
doc = word.ActiveDocument

def create_table
  doc.Tables.Add(word.Selection.Range, 4, 2) #Creates a table with 3 rows and 2 columns
  doc.Tables(1).Borders.Enable = true
end

create_table
4

1 に答える 1

4

あなたの問題は、create_tableメソッド内で、メインスコープにあるがメソッドに渡さなかった変数を参照していたことです。これはあなたが望むもののために働きます:

require 'win32ole'

#setting up the Word
word = WIN32OLE.new('Word.Application')
#Shows the word Application
word.Visible = true
#Setting doc to the active document
doc = word.Documents.Add
doc = word.ActiveDocument

def create_table(d, w)
  d.Tables.Add(w.Selection.Range, 4, 2)
  d.Tables(1).Borders.Enable = true
end

create_table(doc, word)

docおよびの参照が関数に渡されていることに注意してくださいword。また、ところで、4 行 2 列のテーブルを作成しています。

于 2010-12-09T18:26:22.553 に答える