我正在通过ruby做一些word自动化的工作,但我对它相对缺乏经验。我现在正在尝试使我的代码实现功能,但我遇到了这个错误
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发布于 2010-12-10 02:26:23
您的问题是,在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列的表。
https://stackoverflow.com/questions/4395172
复制相似问题