Excel vba msgbox массив

 

ts-79

Пользователь

Сообщений: 246
Регистрация: 15.02.2013

#1

20.02.2014 13:52:25

Доброго дня уважаемые!

Из некой таблицы, при выполнении нескольких условий данные записываются в массив (х строк, 3 столбца)
На лист эксел массив выгружается нормально, но хотел выгрузить этот массив в msgbox
Нашел такой код: (других не нашел)

Код
    Msg = ""
    For j = 1 To UBound(ar2, 1)
        For k = 1 To UBound(ar2, 2)
          Msg = Msg & ar2(j, k) & " "
        Next k
        Msg = Msg & Chr(13)
    Next j
 

Но в msgbox после данных массива добавляются пустые строки столько же сколько строк в исходной таблице, и кнопки ОК не видать.

Как сделать что бы эти пустые строки не отображались в msgbox

Весь код ниже

Скрытый текст

Прикрепленные файлы

  • массив в msgbox.xlsm (26.6 КБ)

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

#2

20.02.2014 13:59:48

Код
For j = 1 To UBound(ar2, 1)
        For k = 1 To UBound(ar2, 2)
          If ar2(j, k) <> "" Then
            Msg = Msg & ar2(j, k) & " "
            Msg = Msg & Chr(13)
        End If
        Next k
    Next j
 
 

Казанский

Пользователь

Сообщений: 8839
Регистрация: 11.01.2013

#3

20.02.2014 14:04:03

Код
Dim stroka As String
    Msg = ""
    For j = 1 To UBound(ar2, 1)
        stroka = ""
        For k = 1 To UBound(ar2, 2)
          stroka = stroka & ar2(j, k) & " "
        Next k
        If Trim$(stroka) <> "" Then Msg = Msg & stroka & Chr(13)
    Next j
 
 

ts-79

Пользователь

Сообщений: 246
Регистрация: 15.02.2013

В таком виде выводятся все значения массива в столбик, а хотелось бы в таком виде

Х 1, Х 2, Х 3
Х+1 1, Х+1 2, Х+1 3
Х+2 1, Х+2 2, Х+2 3
и т.д.

 

ts-79

Пользователь

Сообщений: 246
Регистрация: 15.02.2013

#5

20.02.2014 14:08:10

Казанский, спасибо, то что нужно.

  • #3

Thank you for the quick reply. It seems to still not be working, i may be defining the array wrong. Here is my code, if you could give me any suggestions on defining the array i would appreciate it.
Thank you

Dim lastRow, lastCol As Integer
Dim myarray() As Variant
Dim txt As String
Dim c As Long
With ActiveSheet
lastRow = .Cells(.Rows.count, «D»).End(xlUp).Row
lastCol = .Cells(20, .Columns.count).End(xlToLeft).Column
End With

count = 0
count2 = 0
For i = 20 To lastRow
If Cells(i, 1).Interior.ColorIndex = 4 Then
myarray = Array(Rows(i))
count2 = count2 + 1
End If
For j = 1 To 26
If Cells(i, j).Interior.ColorIndex = 28 Then
count = count + 1
End If
Next j
Next i
If count > 0 Then
MsgBox («Please Fill In Blue Highlighted Cells»), vbOKOnly
End If
For c = LBound(myarray) To UBound(myarray)
txt = txt & myarray(c) & vbCrLf
Next c
MsgBox txt
With Application
.EnableEvents = True
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With

End Sub

  • #5

Thank you for your help. I have it working now
Cheers

Главная » Функции VBA »

28 Апрель 2011              134718 просмотров

  • Array() — позволяет автоматически создать массив нужного размера и типа и сразу загрузить в него переданные значения:
        'инициализируем переменную с типом Variant
        Dim avArr
        'присваиваем переменной значение массива
        avArr = Array("Первый элемент", "Второй элемент", "3", 4, "Последний")
        'показываем 3-ий по порядку элемент
        MsgBox avArr(2)

    Опечатки нет. avArr(2) действительно выдаст третий элемент, т.к. по умолчанию для массива нижняя граница равна нулю. И да, таким образом можно создать исключительно одномерный массив.

  • Filter() — позволяет на основе одного массива получить другой, отфильтровав в исходном массиве нужные нам элементы.
  • LBound() — возвращает информацию о нижней границе массива (то есть номере первого имеющегося в нем значения)
        Dim avArr
        avArr = Array("Первый элемент", "Второй элемент", "3", 4, "Последний")
        'показываем первый элемент
        MsgBox avArr(LBound(avArr))
  • UBound() — возвращает информацию о верхней границе массива (номер последнего имеющегося значения)
        Dim avArr
        avArr = Array("Первый элемент", "Второй элемент", "3", 4, "Последний")
        'показываем последний элемент
        MsgBox avArr(UBound(avArr))
  • Join() — возможность слить множество строк из массива строк в одну строковую переменную. В качестве разделителя по умолчанию используется пробел, можно указать свой разделитель.
        Dim avArr
        avArr = Array("Первый элемент", "Второй элемент", "3", 4, "Последний")
        'объединяем все элементы массива с разделителем "-"
        MsgBox Join(avArr, "-")
  • Split() — обратная функция, разбивающая строку на массив строк . В качестве разделителя по умолчанию используется пробел, можно указать свой разделитель.
        'инициализируем переменную с типом Variant
        'т.к. затем это будет массив
        Dim sStr
        'разбиваем указанный текст массив. Разделитель - "-"
        sStr = Split("Первый элемент-Второй элемент-3-4-Последний", "-")
        'показываем 3-ий по порядку элемент
        MsgBox sStr(2)

Статья помогла? Сделай твит, поделись ссылкой с друзьями!


We know very well that a variable is a container to store a value. Sometimes, developers are in a position to hold more than one value in a single variable at a time. When a series of values are stored in a single variable, then it is known as an array variable.

Array Declaration

Arrays are declared the same way a variable has been declared except that the declaration of an array variable uses parenthesis. In the following example, the size of the array is mentioned in the brackets.

'Method 1 : Using Dim
Dim arr1()	'Without Size

'Method 2 : Mentioning the Size
Dim arr2(5)  'Declared with size of 5

'Method 3 : using 'Array' Parameter
Dim arr3
arr3 = Array("apple","Orange","Grapes")
  • Although, the array size is indicated as 5, it can hold 6 values as array index starts from ZERO.

  • Array Index cannot be negative.

  • VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string, or characters in a single array variable.

Assigning Values to an Array

The values are assigned to the array by specifying an array index value against each one of the values to be assigned. It can be a string.

Example

Add a button and add the following function.

Private Sub Constant_demo_Click()
   Dim arr(5)
   arr(0) = "1"           'Number as String
   arr(1) = "VBScript"    'String
   arr(2) = 100 		     'Number
   arr(3) = 2.45 		     'Decimal Number
   arr(4) = #10/07/2013#  'Date
   arr(5) = #12.45 PM#    'Time
  
   msgbox("Value stored in Array index 0 : " & arr(0))
   msgbox("Value stored in Array index 1 : " & arr(1))
   msgbox("Value stored in Array index 2 : " & arr(2))
   msgbox("Value stored in Array index 3 : " & arr(3))
   msgbox("Value stored in Array index 4 : " & arr(4))
   msgbox("Value stored in Array index 5 : " & arr(5))
End Sub

When you execute the above function, it produces the following output.

Value stored in Array index 0 : 1
Value stored in Array index 1 : VBScript
Value stored in Array index 2 : 100
Value stored in Array index 3 : 2.45
Value stored in Array index 4 : 7/10/2013
Value stored in Array index 5 : 12:45:00 PM

Multi-Dimensional Arrays

Arrays are not just limited to a single dimension, however, they can have a maximum of 60 dimensions. Two-dimensional arrays are the most commonly used ones.

Example

In the following example, a multi-dimensional array is declared with 3 rows and 4 columns.

Private Sub Constant_demo_Click()
   Dim arr(2,3) as Variant	' Which has 3 rows and 4 columns
   arr(0,0) = "Apple" 
   arr(0,1) = "Orange"
   arr(0,2) = "Grapes"           
   arr(0,3) = "pineapple" 
   arr(1,0) = "cucumber"           
   arr(1,1) = "beans"           
   arr(1,2) = "carrot"           
   arr(1,3) = "tomato"           
   arr(2,0) = "potato"             
   arr(2,1) = "sandwitch"            
   arr(2,2) = "coffee"             
   arr(2,3) = "nuts"            
           
   msgbox("Value in Array index 0,1 : " &  arr(0,1))
   msgbox("Value in Array index 2,2 : " &  arr(2,2))
End Sub

When you execute the above function, it produces the following output.

Value stored in Array index : 0 , 1 : Orange
Value stored in Array index : 2 , 2 : coffee

ReDim Statement

ReDim statement is used to declare dynamic-array variables and allocate or reallocate storage space.

Syntax

ReDim [Preserve] varname(subscripts) [, varname(subscripts)]

Parameter Description

  • Preserve − An optional parameter used to preserve the data in an existing array when you change the size of the last dimension.

  • Varname − A required parameter, which denotes the name of the variable, which should follow the standard variable naming conventions.

  • Subscripts − A required parameter, which indicates the size of the array.

Example

In the following example, an array has been redefined and then the values preserved when the existing size of the array is changed.

Note − Upon resizing an array smaller than it was originally, the data in the eliminated elements will be lost.

Private Sub Constant_demo_Click()
   Dim a() as variant
   i = 0
   redim a(5)
   a(0) = "XYZ"
   a(1) = 41.25
   a(2) = 22
  
   REDIM PRESERVE a(7)
   For i = 3 to 7
   a(i) = i
   Next
  
   'to Fetch the output
   For i = 0 to ubound(a)
      Msgbox a(i)
   Next
End Sub

When you execute the above function, it produces the following output.

XYZ
41.25
22
3
4
5
6
7

Array Methods

There are various inbuilt functions within VBScript which help the developers to handle arrays effectively. All the methods that are used in conjunction with arrays are listed below. Please click on the method name to know about it in detail.

Sr.No. Function & Description
1 LBound

A Function, which returns an integer that corresponds to the smallest subscript of the given arrays.

2 UBound

A Function, which returns an integer that corresponds to the largest subscript of the given arrays.

3 Split

A Function, which returns an array that contains a specified number of values. Split based on a delimiter.

4 Join

A Function, which returns a string that contains a specified number of substrings in an array. This is an exact opposite function of Split Method.

5 Filter

A Function, which returns a zero based array that contains a subset of a string array based on a specific filter criteria.

6 IsArray

A Function, which returns a boolean value that indicates whether or not the input variable is an array.

7 Erase

A Function, which recovers the allocated memory for the array variables.

Понравилась статья? Поделить с друзьями:
  • Excel vba msgbox yes no if
  • Excel vba microsoft excel objects
  • Excel vba for each cell in range cells
  • Excel vba for dummy pdf
  • Excel vba for down to