问题描述
我是 VB 新手.我想在单击第一个按钮时将值存储在数组中,并在单击第二个按钮时显示结果.我成功地将值存储在一个数组中.但是我无法在第二个按钮单击事件中访问相同的数组..
I am newbie in 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
任何人都可以帮助我.
推荐答案
Nimmy
我的帖子不是要回答您的主要问题:) 如果您查看 Ken 和 Cody 的评论,那么您将自动意识到答案是什么;)
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 ;)
当我看到你的代码和你是新手的声明时,我忍不住发表了评论.我记得我学习编码的日子,像 SO 这样的论坛实际上帮助我提高了我的编码技能.所以你可以认为这是一种回报:-D
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 you can consider this as a payback :-D
1) 在您的情况下,您可以将 i 作为整数 变暗,但是当您处理更大的行(例如 32768 行)时会发生什么.在 VBA Excel 中工作时,将 i 调暗 是安全的.
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. It's safe to dim i as long when working in VBA Excel.
2) .Select 是在 VBA 中工作时出错的主要原因,更不用说它们会减慢您的代码速度.同样的代码也可以写成下面给出的代码.我假设第一行和最后一行之间没有空白值.
2) .Select are a major cause of errors when working in VBA and not to mention that they slow down your code. 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 是的,快乐编码 ;)
HTH and yes, Happy Coding ;)
席德
这篇关于vb中的按钮点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!