简体   繁体   中英

read only one cell at a time Cell value from Excel vba

I have values in different excel cells Value1, Value2, Value3. In excel Vba I have created one button , and one Label. I want to write a program such that when I click the button each time Label value should change accordingly Value1, Value2, Value3 . But with this code when I click Button 1 I see Value 1 only and when I click second time nothing happens. I have tried to do it with Do loop and then again when I click Button it goes to the last cell automatically :

   Private Sub Button1_Click()
    Dim i As Integer
    i = 1
    Do
    Label1.Caption = Cells(i, 2)
    i = i + 1
    Loop Until i = 10
   End Sub

You need a pointer of some kind to the last cell used, and a method of incrementing (and wrapping around) each time the button is pressed.

If the pointer position needs to persist after closing the workbook, you will need to store the pointer in some cell (I suppose you could use the registry if that were not possible; but I'd rather use a cell on a hidden worksheet).

If you just need the pointer to persist while the workbook is open, and it is OK for it to reset to the first cell each time the workbook is re-opened, then you can store it in a global or static variable within your VBA module.

Here is an example using a Static variable. A similar process could be applied if you were storing the variable in a cell. This routine assumes that you are cycling through cells B1:B10 on the same sheet as the button.

Option Explicit
  Private Sub CommandButton1_Click()
  Static NextCellRow As Long
NextCellRow = NextCellRow Mod 10 + 1
CommandButton1.Caption = Cells(NextCellRow, 2)
End Sub

One other caveat: NextCellRow will also forget it's value if there is an unhandled VBA error in your routine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM