Как мне остановить цикл от повторения последнего значения дважды? - PullRequest
0 голосов
/ 08 июня 2019

При запуске цикла последнее значение всегда передается дважды независимо от количества строк.

Я пытался .offset и +/- до последней строки.

Public MySession As Reflection.Session
Option Explicit

Sub getData()

Dim ws As Worksheet
Dim lastrow As Long
Dim i As Long
Dim question As String
Dim answer As String

Set ws = ThisWorkbook.Sheets("Sheet1")
Set MySession = New Reflection.Session

With ws
    lastrow = getlastrow
    With MySession

        On Error GoTo qHandle
        For i = 2 To lastrow
            question = ws.Cells(i, 1).Value

            On Error GoTo aHandle
            If question = "" Then
                'do nothing
            Else
                .TransmitANSI question
                .TransmitTerminalKey rcIBMEnterKey
                ws.Cells(i, 2).Value = MySession.GetDisplayText(1, 2, 3)
            End If
            On Error GoTo 0

        Next i
        On Error GoTo 0

    End With
End With

Exit Sub

qHandle:
    MsgBox "There was a problem with the question, " & Err.Description
    Exit Sub

aHandle:
    MsgBox "There was a problem with the answer, " & Err.Description
    Exit Sub

End Sub

Конечным результатом должна быть печать значений на листе, соответствующем строке ввода.Все работает без ошибок, но последнее значение повторяется дважды, что приводит к появлению дополнительной строки в столбце 2, но не в столбце 1.

Это моя функция для получения lastrow.

'Return Value of Last Row
Public Function get_LastRow() As Long
Dim LastRow As Long
With ActiveSheet
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
        LastRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).row
    Else
        LastRow = 1
    End If
    get_LastRow = LastRow
End With
End Function

1 Ответ

1 голос
/ 08 июня 2019

Возможно, это не решает вашу проблему, но здесь:

Set ws = ThisWorkbook.Sheets("Sheet1")
Set MySession = New Reflection.Session

With ws
    lastrow = getlastrow

... нет никакой связи между ws и lastrow, если только ws не является активным листом (и полагается наэто сделает ваш код подверженным проблемам)

Это было бы лучше:

lastrow = getlastrow(ws)

и

Public Function get_LastRow(ws As Worksheet) As Long
Dim LastRow As Long
With ws
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
        LastRow = .Cells.Find(What:="*", _
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...