2

如何使用 Word 宏从 Excel 和过去复制未定义的范围到 Word 文档中。我尝试了以下但无法成功。你能帮我么。

注意:如果我提到它工作正常的范围,而我想NumberOfRows = .Range("A65536").End(xlUp).Row在 word 宏中使用代码 - 我得到运行时错误 1004。

Sub InputExcel()

Set appExcel = CreateObject("Excel.Application")

Dim INP_File As Variant
Dim lngRows As Long
Dim LenMgs As Long
Dim NumberOfRows As String

INP_File = appExcel.GetOpenFilename("Excel files (*.xlsx;*.xls),*.xlsx;*.xls", 2)

appExcel.Workbooks.Open INP_File

If INP_File > 0 Then

    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "Sample"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    Selection.HomeKey Unit:=wdLine

    LenMgs = appExcel.Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count
    'NumberOfRows = appExcel.Worksheets("Sheet1").Range("A65536").End(xlUp).Row
    Set Rng = appExcel.Worksheets("Sheet1").Range(appExcel.Worksheets("Sheet1").Cells(4, 1), appExcel.Worksheets("Sheet1").Cells(LenMgs, 5))
    'Rng.Copy
    'appExcel.Worksheets("Sheet1").Range("A1:B5").Copy - This is working !! if I specify the range.
    Selection.Paste

End If
appExcel.ActiveWorkbook.Close

appExcel.Quit

Set appExcel = Nothing

End Sub
4

1 回答 1

2

您收到错误是因为xlUp它是一个 Excel 常量,并且当您使用后期绑定与 Excel 连接时,MS Word 无法识别它。

您必须将其声明为代码的顶部

Const xlup = -4162 

此外,您可能想阅读THIS以查找 Excel 中的最后一行?

于 2013-09-16T11:32:00.123 回答