简体   繁体   English

一次仅读取一个单元格来自Excel vba的单元格值

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

I have values in different excel cells Value1, Value2, Value3. 我在不同的Excel单元格Value1,Value2,Value3中有值。 In excel Vba I have created one button , and one Label. 在excel Vba中,我创建了一个按钮和一个标签。 I want to write a program such that when I click the button each time Label value should change accordingly Value1, Value2, Value3 . 我想编写一个程序,这样每次单击按钮时,Label值应相应地更改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. 但是使用此代码,当我单击“按钮1”时,我只能看到“值1”,而当我第二次单击时,则什么也没有发生。 I have tried to do it with Do loop and then again when I click Button it goes to the last cell automatically : 我尝试使用Do循环来执行此操作,然后再次单击Button时,它会自动转到最后一个单元格:

   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. 如果您只需要指针在工作簿打开时保持不变,并且可以在每次重新打开工作簿时将其重置到第一个单元格,则可以将其存储在VBA模块中的全局变量或静态变量中。

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. 此例程假定您正在循环浏览按钮同一页上的单元格B1:B10。

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. 另一个警告:如果例程中有未处理的VBA错误,则NextCellRow也会忘记其值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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