Ruby - WIN32OLE 函数创建

标签 ruby ms-word ole win32ole

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

最佳答案

您的问题是,在您的 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 列的表格。

关于Ruby - WIN32OLE 函数创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4395172/

相关文章:

ruby-on-rails - ruby-1.9.3-p125 ssl 错误

ruby-on-rails - Ruby on Rails ActiveModel::MassAssignmentSecurity::错误

ruby-on-rails - 缺少新 Rails 3 应用程序的模板?

arrays - 字典中每个项目的第一个成员需要是一个数组

ms-word - 如何在Word中获取列表级别(使用Pandoc+Markdown)

第三方组件的 COM 代理

c++ - 使用 Embarcadero C++ (Builder) 从 Word OLE 中检索和循环故事范围

ruby-on-rails - 无法安装 charlock_holmes-0.6.9.4

c# - 分析 word 文档中的文本 - 如何让它忽略书签?

Delphi、OleVariant 作为输出参数