这是我制作的宏。
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
我手动过滤了信息,我想将所选行打印为仅字。不幸的是,这个宏总是从第1行开始。 如何在Word中仅打印选定的行? 谢谢你的帮助。
答案 0 :(得分:1)
您需要遍历可见单元格的区域,然后遍历每个区域内的行。
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
答案 1 :(得分:0)
如何使用For Each
迭代可见单元格,如下所示:
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