我正在学习VBA,
我在sheet1中有18行5列数据,Sheet2 3行8列
我想循环数据并在NOTEPAD中打印,例如
这是我的代码,
Sub Looping()
Dim str As String
Dim MaxStrLen As String
Dim rest As Integer
Dim Lstr As Integer
Dim LMstr As Integer
Dim MStr As Integer
Dim LR As Range
Dim CNT As Integer
Dim LastRow As Long
Dim LastCol As Long
Dim LRow As Long
Dim LCol As Long
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim i As Long
Dim j As Long
Dim Page_Break As Long
Dim k As Long
Dim PB As Long
Dim x As Long
Dim y As Long
Dim rng As Range
Set rng = Range("A1:E6")
Dim FilePath As String
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
Set ws3 = Sheets("Sheet3")
Open "C:\Users\Antony\Music\Excel Macros\Test.txt" For Output As #2
'''''FIRST FIVE LINES WILL PRINT IN THE NOTEPAD
With ws1
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
LRow = ws2.Cells(.Rows.Count, 1).End(xlUp).Row
LCol = ws2.Cells(1, .Columns.Count).End(xlToLeft).Column
BlkSize = 6 'data consists of blocks of 6 rows
For i = 1 To LastRow
sOut = vbNullString
LengthRow = i
Do While LengthRow > BlkSize
LengthRow = LengthRow - BlkSize
Loop
'LengthRow points to row where char length is to be taken from
For j = 1 To LastCol
str = .Cells(i, j).Value
If str <> Empty Then
MStr = ws2.Cells(LengthRow, j).Value
Lstr = Len(str)
rest = MStr - Lstr
sOut = sOut & str & Space(rest)
Else
MStr = ws2.Cells(LengthRow, j).Value
Lstr = Len(str)
rest = MStr - Lstr
sOut = sOut & str & Space(rest)
End If
Next
Print #2, sOut
Next
End With
'''''LAST LINE WILL PRINT IN THE SAME NOTEPAD
With ws3
LRow = .Cells(.Rows.Count, 1).End(xlUp).Row
LCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
slast = vbNullString
For k = 2 To LRow
str = Join(Application.Transpose(Application.Transpose(.Cells(k, "A").Resize(1, LastCol).Value)), "@#")
str = Replace(str, "=", vbNullString)
Print #2, str
Next
Endtext = "EODR"
Print #2, slast & Endtext
End With
'Loop
Close #2
End Sub
答案 0 :(得分:0)
你可以嵌入循环:
For i = 0 to 2
For j = 1 to 6
Write Sheet1 row = i * 6 + j to file 'this line not actual code
Next j
Write Sheet2 row = i + 1 to file 'this line not actual code
Next i