直到ActiveCell为空

时间:2017-06-02 13:27:36

标签: excel-vba vbscript vba excel

使用下面的代码我试图从XLS(initialVal)复制一个值并粘贴到GUI文本字段。然后,我想进入一个循环并使用ActiveCell调用和偏移(向下移动一行)获取下一个值(nextVal)。 我想继续检索(并粘贴到GUI)下一行(同一列)中的下一个值,直到找到一个空单元格。

使用下面我正在处理的代码,它将初始值粘贴(2,7),但随后它会不断地粘贴(在无限循环中)第一个 行/列并没有似乎通过值增加/偏移,即预期是:

(2,7) Initial Value
(3,7) Next Value
(4,7) Next Value
(5,7) Next Value
(6,7) Next Value etc etc until empty
Set objExcel = CreateObject("Excel.Application")
Set objWb = objExcel.Workbooks.Open("C:\test.xlsx")
Set objSheet = objWb.Worksheets("sheet1")

Set initialVal = objSheet.Cells(2, 7)

'At this point code (TBC, not required to highlight this issue) will paste the
'initialVal to a text field in the GUI and subsequently clear/delete the field

Sub test1()
    Set nextVal = ObjExcel.ActiveCell

    Do Until IsEmpty(nextVal)
        nextVal.Offset(1, 0).Select
        'Again, at this point the code will paste the nextVal to the GUI (and
        'subsequently clear it) , loop back and move down one cell and paste that
        'next cell until it hits an empty cell and come out of the loop
    Loop
End Sub

Call test1

1 个答案:

答案 0 :(得分:1)

我没有改变逻辑中的任何内容。只是纠正错误。

将您的子重写为:

Sub test1()
    initialVal.offset(1,0).Select         'You have to move 1 cell down from your initial cell  
    Set nextVal = objExcel.ActiveCell
    Do until IsEmpty(nextVal)

        '----------->GUI pasting code<---------------

        nextVal.Offset(1, 0).Select
        Set nextVal = objExcel.ActiveCell    
    Loop
End Sub

这是实现这项工作的另一种方式。它不需要选择单元格并一次又一次地执行偏移。您可以直接从单元格中获取所需的值。

Dim objExcel, objWb, objSheet, rows, i, tempVal
Set objExcel = CreateObject("Excel.Application")
Set objWb = objExcel.Workbooks.Open("C:\test.xlsx")
Set objSheet = objWb.Worksheets("sheet1")
rows = objSheet.usedrange.rows.count
for i=2 to rows step 1
    tempVal = objSheet.Cells(i,7)
    If IsEmpty(tempVal) then
        Exit For 
    Else
        'Call your function which pastes the tempVal to GUI
    End If  
Next
objWb.Close
objExcel.Quit
Set objSheet = Nothing
Set objWb = Nothing
Set objExcel = Nothing