【问题标题】:How to Loop the data which is in sheet1 based on sheet2 reference and print in notepad如何根据 sheet2 引用循环 sheet1 中的数据并在记事本中打印
【发布时间】:2018-09-01 10:15:48
【问题描述】:

我有两个工作表。 sheet1 有数据, sheet2 有最大长度 引用 sheet1 中数据的每个单元格。

我可以循环一次,但不能循环循环第二组消息

Sheet1 有 2 组数据,从第 1 行到第 6 行和第 7 行到第 12 行 https://i.stack.imgur.com/Jyids.jpg

Sheet2 具有最大字符长度,它必须用于第 7 到 12 行 https://i.stack.imgur.com/7JbBC.jpg

输出应该是这样的 https://i.stack.imgur.com/p9dQ5.jpg

Sheet1 第 1 到 6 行指的是 sheet2,但我无法循环相同 7到12的参考。

请注意 在记事本中,应在 EODR 之后打印第二条消息。

我的代码是, 子我自己()

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 h As Long
Dim k As Long

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

'''''前五行将打印在记事本中

With ws1
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

For i = 1 To LastRow
    sOut = vbNullString
    For j = 1 To LastCol
        str = .Cells(i, j).Value
        MStr = ws2.Cells(i, j).Value
        Lstr = Len(str)
        rest = MStr - Lstr
        sOut = sOut & str & Space(rest)
    Next
    Print #2, sOut
Next
End With

'''''最后一行将打印在同一个记事本中

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


Close #2

End Sub

如果有更多消息,我需要循环,请帮我解决

【问题讨论】:

  • 谁能帮我解决这个问题

标签: vba excel excel-formula


【解决方案1】:

解决这个问题

Sheet1 第 1 行到第 6 行引用了 sheet2,但我无法为 7 到 12 循环相同的引用。

这样修改中间块:

BlkSize=6              ' your data consists of blocks of 6 rows
For i = 1 To LastRow
    sOut = vbNullString
    LengthRow = i
    Do While LengthRow > BlkSize
        LengthRow = LengthRow - BlkSize
    Loop
' now LengthRow points to row where char length is to be taken from
    For j = 1 To LastCol
        str = .Cells(i, j).Value
        MStr = ws2.Cells(LengthRow, j).Value
        Lstr = Len(str)
        rest = MStr - Lstr
        sOut = sOut & str & Space(rest)
   Next
   Print #2, sOut
Next

【讨论】:

  • @AcsEmo 这就是我想要的,而且它工作正常。谢谢
猜你喜欢
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多