VBA:使用从excel到Word的筛选行运行宏

VBA:使用从excel到Word的筛选行运行宏,vba,excel,Vba,Excel,这是我制作的宏 Sub SelectingForWord() Dim NomDoc As String, oWord As Word.Application, oDoc As Word.Document Dim i As Long Dim lastRow As Long Dim x As Integer 'open WORD Set oWord = CreateObject("word.Application") oWord.Documents.Open (ThisWorkbook.Path

这是我制作的宏

Sub SelectingForWord()
Dim NomDoc As String, oWord As Word.Application, oDoc As Word.Document
Dim i As Long
Dim lastRow As Long
Dim x As Integer

'open WORD
Set oWord = CreateObject("word.Application")
oWord.Documents.Open (ThisWorkbook.Path & "\04_Publi_002_2018.docx")
oWord.Visible = True
oWord.Activate
oWord.Selection.Goto what:=wdGoToBookmark, Name:="FromExcel"

'writing on my word document
With oWord.Selection
'lastRow = Sheets("BASE").Range("A" & Rows.Count).End(xlUp).Row
'lastRow = Sheets("BASE").Range(xlCellTypeVisible).Count

'find last row
lastRow = Sheets("BASE").Range("A" & Rows.Count).End(xlUp).Row
x = lastRow

'count visible rows
RowCount = Range("a1:a" & x).Rows.SpecialCells(xlCellTypeVisible).Count - 1

For i = 2 To RowCount      
 'Doing things to print in Word
        .TypeText Cells(i, 1) & Chr(9) & Cells(i, 2) & " " & Cells(i, 3) & " (" & Cells(i, 5) & "-" & Cells(i, 18) & ") and " & Cells(i, 15) & " " & Cells(i, 16) & Chr(9) & Cells(i, 14) & Chr(9) & Cells(i, 13)
        .TypeParagraph
Next i
End With
End Sub
我已经手动筛选了信息,我只想将所选行打印到word。不幸的是,这个宏总是从第1行开始。 如何仅在Word中打印选定的行?
谢谢您的帮助。

您需要在可见单元格区域中循环,然后在每个区域中循环行

dim a as long, r as long

with Range("a1:a" & x)
    with .resize(.rows.count-1, .columns.count).offset(1, 0)
        for a=1 to .SpecialCells(xlCellTypeVisible).areas.count
            with .SpecialCells(xlCellTypeVisible).areas(a)
                for r=1 to .rows.count
                    oWord.Selection.TypeText .Cells(r, 1) & Chr(9) & .Cells(r, 2) & " " & _
                              .Cells(r, 3) & " (" & .Cells(r, 5) & "-" & _
                              .Cells(r, 18) & ") and " & .Cells(r, 15) & " " & _
                              .Cells(r, 16) & Chr(9) & .Cells(r, 14) & Chr(9) & .Cells(r, 13)
                    oWord.Selection.TypeParagraph
                next r
            end with
        next a
    end with
end with

对每个使用
在可见单元格中进行迭代,如下所示:

Option Explicit

Public Sub RunThroughVisibleRowsOnly()
    ' Demonstrates how to process only the visible rows in the used area of a worksheet

    ' Reference to the worksheet
    Dim oSheet As Worksheet
    Set oSheet = Sheets("BASE")

    ' xCell will be our variable for the For Each loop
    Dim xCell As Range

    ' Get the last row
    Dim iLastRow As Long
    iLastRow = oSheet.Cells.SpecialCells(xlCellTypeLastCell).Row

    ' Find all the cells in the used range of column A
    ' that are visible, and process each row
    For Each xCell In oSheet.Range("A1:A" & iLastRow).SpecialCells(xlCellTypeVisible)

        '// For testing: report the row
        Debug.Print xCell.Address, xCell.Row

    Next
End Sub