【问题标题】:Ruby - WIN32OLE function creationRuby - WIN32OLE 函数创建
【发布时间】:2010-12-09 05:30:28
【问题描述】:

我正在通过 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

【问题讨论】:

  • 如果你记得缩进你的代码,你忘记将doc作为参数传递会更明显。

标签: ruby ms-word ole win32ole


【解决方案1】:

您的问题是,在您的 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)

请注意,它现在将 docword 的引用传递给函数。另外,顺便说一下,您正在创建一个 4 行 2 列的表。

【讨论】:

  • 为此干杯,到目前为止,我在编程之旅中只接触过 R,所以我对 ruby​​ 中的工作原理一无所知。另外,是的,我需要在原始代码中更新我的 cmets,这只是我从主脚本中复制的一段代码,此后一直在编辑。
猜你喜欢
  • 1970-01-01
  • 2010-10-08
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
相关资源
最近更新 更多