获取excel FROM Word宏中的ActiveCell值

时间:2013-07-23 06:37:24

标签: vba excel-vba word-vba excel

我试图用word来操作excel工作簿。一切都很顺利,直到突然间我无法得到ActiveCell.Value的响应

问题一直发生在这段代码的底部,我试图在msgbox中显示值,但没有出现msgbox。

以前的命令如:

worksheetJobs.Activate

.Cells(1500, fichierColumn).Select

工作正常。

奇怪的是我正在研究这个问题(在我发布的内容之后有一整段代码)然后突然间我甚至无法得到这个非常基本的东西来回应......

    Dim excelObj As Excel.Application
    Dim oWB As Excel.Workbook

    'If Excel is running, get a handle on it; otherwise start a new instance of Excel
    On Error Resume Next
    Set excelObj = GetObject(, "Excel.Application")

    If Err Then
        MsgBox "excel is not running"
        Set excelObj = New Excel.Application
        excelObj.Visible = True

        On Error GoTo Err_Handler
        Set oWB = excelObj.Workbooks.Open(Filename:=todoWorkbook)

    Else
        MsgBox "excel is running"
        Dim wb As Workbook
        For Each wb In excelObj.Workbooks
            If wb.Name = toDoName Then
                Set oWB = wb
                Exit For
            End If
        Next wb
    End If

    MsgBox oWB.Name

    Dim fichierColumn As Integer
    Dim outMots As Integer
    Dim outLignes As Integer
    Dim langOut As Integer

    fichierColumn = 5
    outMots = 17
    outLignes = 18
    langOut = 9

    Dim worksheetJobs As Excel.Worksheet
    Set worksheetJobs = oWB.Worksheets("Liste jobs")
    worksheetJobs.Activate

    With worksheetJobs
        .Cells(1500, fichierColumn).Select
        Dim tempStr As String

        tempStr = ActiveCell.Value
        MsgBox tempStr

    End With

    'Set excelObj = Nothing
    'Set oWB = Nothing
    Exit Sub

Err_Handler:
   MsgBox todoWorkbook & " caused a problem. " & Err.Description, vbCritical, _
       "Error: " & Err.Number

End Sub

1 个答案:

答案 0 :(得分:2)

由于几个原因,您没有在消息框中获取值。您的细胞参考几乎就在那里,但ActiveCellExcel.Application的属性。 VBA认为ActiveCell来自Word对象模型,而不是Excel,因为您没有从Excel中明确指定它。

由于您的第一行之一是On Error Resume Next,所有错误都被压抑,而您没有遇到ActiveCell的非限定引用错误。因此,word将tempStr的空白字符串传递给您的消息框。

以下内容适用于您

tempStr = excelObj.ActiveCell 

应该注意的是,您不需要Select个单元格来获取它们的值。以下将产生相同的结果:

tempStr = worksheetJobs.Cells(1500, fichierColumn).Value