简体   繁体   English

VB中的按钮单击事件

[英]Button click event in vb

I am newbie in VB. 我是VB的新手。 I want to store the values in an array when I am clicking the first button and show the result when I am clicking the second button. 单击第一个按钮时,我想将值存储在数组中;单击第二个按钮时,我要显示结果。 I am successfully stored the values in an array. 我已成功将值存储在数组中。 But i cant access the same array in the second button click event.. 但是我无法在第二个按钮单击事件中访问相同的数组。

Dim i As Integer
Dim ag(0 To 7000) As String
Dim bg(0 To 7000) As String

Private CommandButton1_Click()
  i = 0

  Sheets("New").Select
  Range("B2").Select

  While Not IsEmpty(ActiveCell)
    ag(i) = ActiveCell.Value
    i = i + 1
    ActiveCell.Offset(1, 0).Select
  Wend

  i = 0

  Sheets("New").Select
  Range("D2").Select

  While Not IsEmpty(ActiveCell)
    bg(i) = ActiveCell.Value
    i = i + 1
    ActiveCell.Offset(1, 0).Select
  Wend
End Sub

Private CommandButton2_Click()
  UserForm1.Hide
End Sub

Private Sub Cell_Click()
End Sub

Private Sub CommandButton1_Click()
End Sub

Private Sub CommandButton2_Click()
End Sub

Any one can help me please. 任何人都可以帮助我。

Nimmy 尼米

My post is not about answering your main question :) If you look at Ken's and Cody's comment then you will automatically realize what the answer is as ;) 我的帖子不是要回答您的主要问题:)如果您查看Ken和Cody的评论,那么您将自动意识到答案是;;)

I couldn't help comment when I saw your code and your statement that you are a newbie. 当我看到您的代码和声明您是新手时,我不禁发表评论。 I remember my days when I was learning coding and forums like SO actually helped me enhance my coding skills. 我记得我在学习编码的时候,像SO这样的论坛实际上帮助我提高了编码技能。 So you can consider this as a payback :-D 因此,您可以将其视为回报:-D

1) In your case it is ok that you have dimmed i as integer but what happens when you are dealing with rows which are much bigger for example 32768 rows. 1)在您的情况下,可以将i变暗为整数,但是在处理更大的行(例如32768行)时会发生什么。 It's safe to dim i as long when working in VBA Excel. 在VBA Excel中工作时,只要我昏暗就可以了。

2) .Select are a major cause of errors when working in VBA and not to mention that they slow down your code. 2).Select是在VBA中工作时导致错误的主要原因,更不用说它们会使您的代码变慢。 The same code can also be written as the code given below. 相同的代码也可以编写为下面给出的代码。 I am assuming that there is no blank values in between the 1st row and the last row. 我假设第一行和最后一行之间没有空白值。

Dim i As Long
Dim ag(0 To 7000) As String
Dim bg(0 To 7000) As String
Dim ws As Worksheet

Private CommandButton1_Click()
    Set ws = Sheets("New")

    With ws
        For i = 2 To .Range("B" & .Rows.Count).End(xlUp).Row
            ag(i) = .Range("B" & i).Value
        Next
        For i = 2 To .Range("D" & .Rows.Count).End(xlUp).Row
            bg(i) = .Range("D" & i).Value
        Next
    End With
End Sub

HTH and yes, Happy Coding ;) HTH是的,快乐编码;)

Sid 席德

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

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