Excel vba задать массив констант

vashin

0 / 0 / 0

Регистрация: 21.07.2007

Сообщений: 47

1

Как задать массив констант

09.01.2008, 19:51. Показов 19906. Ответов 11

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте!
————-
У меня такая проблема. Я не знаю как задать массив констант с присвоением значений.

Хочу получить примерно следующее:

Visual Basic
1
массив Chisl = ('один','два','три','четыре','пять','шесть')

но не хочу задавать каждый эл-т массива отдельно, например

Visual Basic
1
2
3
4
5
Chisl(1)='один'
Chisl(2)='два'
.
.
Chisl(6)='шесть'

Заранее благодарен. =Миша



0



sharig

2 / 2 / 1

Регистрация: 30.07.2007

Сообщений: 206

11.01.2008, 04:27

2

Для версии VB 6.0.
тогда создай файл на диске, в который впиши все значения твоих констант, а дальше… используй пример ‘записи данных из файла на диске в массив’, который в скором времени будет размещен на сайте VBcode.FAQ (http://sharig.webzone.ru)
Необходимое пояснение: про использование функции Split можно прочитать здесь — http://sharig.webzone.ru/global/pages/Function.htm
В случае следующего примера, впиши все свои константы в файл через абзац:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Private Sub Command1_Click()
Dim txt ' As Long
Dim FN As Integer
FN = FreeFile
Dim FName As String
FName = 'D:1.txt'
Open FName For Input As #FN
txt = Input(LOF(FN), #FN)
Close #FN
Dim str1() As String
str1 = Split(txt, vbCrLf)
For i = 0 To UBound(str1()) - 1
MsgBox str1(i)
Next
End Sub



0



CyberUser

4 / 4 / 2

Регистрация: 15.06.2012

Сообщений: 18

15.06.2012, 15:19

3

Цитата
Сообщение от vashin
Посмотреть сообщение

У меня такая проблема. Я не знаю как задать массив констант с присвоением значений.

Visual Basic
1
2
3
4
5
6
7
8
Option Base 1
DIM Chisl As Variant
.
.
Chisl=Array ("один","два","три","четыре","пять","шесть")
.
.
Form1.Print Chisl(6)



0



Апострофф

Заблокирован

15.06.2012, 15:25

4

CyberUser, Вам не кажется, что Ваш ответ несколько запоздал[/OFF]



0



4 / 4 / 2

Регистрация: 15.06.2012

Сообщений: 18

15.06.2012, 15:39

5

Цитата
Сообщение от Апострофф
Посмотреть сообщение

CyberUser, Вам не кажется, что Ваш ответ несколько запоздал[/OFF]

Да, Миша уже наверное уже с бородой и служит где-нибудь сисадмином.
Но я сам только что озадачился такой проблемой, гугл вывел на эту ветку. Я понял, что тема не раскрыта.
Немного подумав решил, что мое решение будет оптимально. Ну и расшарил идею… Не создавать же новую тему.



0



Эксперт Hardware

3139 / 1907 / 323

Регистрация: 25.10.2011

Сообщений: 5,541

15.06.2012, 15:57

6

Насколько я знаю в вб массива констант нет, а жаль.
Есть одиночная константа или глобальный массив, как в примере.



0



Catstail

Модератор

Эксперт функциональных языков программированияЭксперт Python

34702 / 19224 / 4037

Регистрация: 12.02.2012

Сообщений: 32,180

Записей в блоге: 13

15.06.2012, 16:53

7

Да вот так:

Visual Basic
1
arr=Array("раз","два","три","четыре")  ' и т.д.

Только помни, что «раз» будет иметь индекс 0. А если так:

Visual Basic
1
arr=Array("","раз","два","три","четыре")  ' и т.д.

то «раз» будет иметь индекс 1



0



es geht mir gut

11264 / 4746 / 1183

Регистрация: 27.07.2011

Сообщений: 11,437

15.06.2012, 16:58

8

Цитата
Сообщение от CyberUser
Посмотреть сообщение

Option Base 1

Catstail, внимательнее.



0



Модератор

Эксперт функциональных языков программированияЭксперт Python

34702 / 19224 / 4037

Регистрация: 12.02.2012

Сообщений: 32,180

Записей в блоге: 13

15.06.2012, 17:02

9

А я не использую Option Base… Имею право. И это не вопрос внимания/невнимания.



0



4 / 4 / 2

Регистрация: 15.06.2012

Сообщений: 18

16.06.2012, 00:26

10

Не спорьте мальчики.
Такие мелочи вылазят на первом же тестовом прогоне и сразу правятся.



0



Модератор

Эксперт функциональных языков программированияЭксперт Python

34702 / 19224 / 4037

Регистрация: 12.02.2012

Сообщений: 32,180

Записей в блоге: 13

16.06.2012, 13:27

11

Поучи, поучи…



0



Почетный модератор

21371 / 9105 / 1082

Регистрация: 11.04.2010

Сообщений: 11,014

16.06.2012, 21:06

12

Ладно тему подняли 2001 года, но флудить в ней — это уже через край.
Закрыто



1



dk

MrExcel MVP


  • #2

I’d be very suprised if you could do this. You’d be better off using a variable array, or a custom function which returns the number of days in a given month.

  • #3

I need to revisit this question. There is a need for arrays of constants. I need to add some cells to a worksheet to show average, min, and max. The worksheet is quite asymetrical and the columns to be evaluated are not definable. Here is what I have been able to do as a workaround.

Code:

Dim Evaluation_Array As Variant
Evaluation_Array = Array(3, 4, 5, 6, 8, 11, 15)

For Each Sum_Column_Number In Evaluation_Array

   Call Build_Evaluation_Cell(My_Worksheet, _
                              Sum_Column_Number, _
                              Sumation_Row, _
                              Top_Sumation, _
                              Bottom_Sumation)
Next

The subroutine (in part) adds a summing cell in a row for each of the columns specified. There is more to this, but I hope the code extract above will convey the general concept.

Evaluation_Array really should be an integer, not a variant, as should be Sum_Column_Number. The use of variant requires that the subroutine be declared with a variant rather than an integer.

The original post is approaching five years old now. Can an array of constants be declared?

  • #4

I don’t understand why you would need to do this.

What is the difference between defining this array as a constant, and just defining it by hardcoding the values in to be compiled at run time?

It makes no difference as far as I can see…

You can have the array as an integer, there is no problem there either…. so long as you know the array will be a predetermined length.

e.g.

Code:

option base 1
dim myarray(3) as integer
myarray(1) = 3 : myarray(2) = 4: myarray(3) = 5

Even if you don’t know it would be a pre-determined length, you can use the

keyword to extend the array as and when required.

Am I missing something here?

  • #5

Then again, why do you need the array of days in a month at all? Couldn’t you just use:

Code:

Dim monthnum As Integer
monthnum = 2
MsgBox Day(DateSerial(2006, monthnum + 1, 0))

or similar?

  • #6

Question: Why do we need to be able to declare an array of constants?

First, for the same reason that we need constants, we need an array of constants. And for all of those reasons. I don’t want to build it a run time, I want it predefined at compile time. I have some deadlines and don’t have time to entertain that discussion right now. Get a few books on software engineering and read about software design and constants. Read about writing software for flexibility, robustness and maintainability.

Please bear in mind that example code posted here is often a vehicle used to convey a complex idea. The simplest possible code segment that can convey the question is posed, the often huge amount of complexity behind it is deliberatly omitted. Because the quesion is simple does not mean that the needs are simple.

For now I take it that there is no declaration of constant arrays and will move on. I appreciate the time you took to respond and will leave this thread monitored.

  • #7

It’s not exactly the an array when it’s set as a constant, but the below has similar effects to what you ask:

Code:

Const z As String = "1, 2, 3, 4, 5, 6, 7"

Sub Test()
    x = Split(z, ",")
    For y = LBound(x) To UBound(x)
        MsgBox x(y)
    Next
End Sub

  • #8

First, for the same reason that we need constants, we need an array of constants. And for all of those reasons. I don’t want to build it a run time, I want it predefined at compile time. I have some deadlines and don’t have time to entertain that discussion right now. Get a few books on software engineering and read about software design and constants. Read about writing software for flexibility, robustness and maintainability.

I read your response with interest.

First and foremost, this is a discussion forum where people offer help to others for free. I am not being paid to sit here and read your posts, I do it for the love of helping people out.

If you read many of the posts on this forum, as I have, you will notice a trend with posts. That trend is that people often ask questions, under the presumption that the question they pose will help them fix their solution. All to often, however, it emerges that if more detail is given on the actual problem (as opposed to the solution they believe will fix it), other caveats to the problem can be unearthed that lead to the conclusion that the OP’s question can actually be reposed in another form, leading to an answer that satisfies what is the orginal issue.

I stated I did not understand why you would want an array of constants. To this point, I still don’t understand your intentions. If your motivation was made clearer, then as you say, we could cut through this whole portion of analysis and simply offer you solutions that achieve what you want.

I have to take significant issue with your tone. You know nothing about anyones software development history on this board. As it happens I am a graduate in Computer Science from a top UK university. I do not need your patronising advice on getting some ‘books on software design’. I am very aware of software design principles. I work as a software designer here in London, with Java and C++, as well as a little dabbling in VBA. I have answered numerous posts on this forum with no complaints from the OP’s who have got things working as a result. You cannot declare a constant array in VBA. I could have left it there, but decided to try and explore your problem and offer alternative solutions that could act as a workaround for you. Sure constants are only evaluated once as opposed to everytime a variable is used. Yes, there is an overhead to that, but if its important as you say it is, you can use a variable to hold the array, and then use some (now its my time to get patronising) common sense to leave the array alone at run time, and therefore protect its values.

Furthermore, with this high and mighty attitude you seem to have, I would expect you would get little help from the people on this board. This is a community that involves mutual respect, and a culture of helpfulness and learning. Both myself, and Oaktree (a Microsoft most valued professional) have taken the time out of our lives to attempt to address your problem, to try and talk you through your thought process so as to ascertain not only what you want, but why you want it as well. Frankly I find your consequent posts abhorrently patronising and full of negativity.

My advice — change your attitude, and fast, else you’ll find yourself going down in a very negative fashion not only on this medium, but in life in general.

Good day to you.

  • #9

Hi bkelly

1. I agree with you. We should be able to define constant arrays. Whenever the language allows it I define most of the constants at the beginning of the modules, outside the routines.

2 . It is not true what you say: «The use of variant requires that the subroutine be declared with a variant rather than an integer.»

You can (should) use a type conversion function and define the subroutine properly.

Try this:

Code:

Sub ConvType()
Dim v As Variant

    v = 2
    Call paramtype(CInt(v))
End Sub

Sub paramtype(i As Integer)

    MsgBox i & ", " & TypeName(i)
End Sub

3. You can use a workaround like BJungheim’s. This will let you define the constant array at the beginning of the module

Code:

Const sArr As String = "1,3,5,7"

Sub a()
Dim v

For Each v In Split(sArr, ",")
    MsgBox CInt(v)
Next
End Sub

4 — It might be better if along with a syntax question you would explain your problem.
There may be other ways of doing what you want that may be more efficient and easier to implement.

In this case, although I don’t have enough information about your problem, I got the feeling that maybe you could use a multiarea range.
If you had explained your problem better, I might be able suggest it or understand that it makes no sense

5. Last but not least:

I have some deadlines and don’t have time to entertain that discussion right now. Get a few books on software engineering and read about software design and constants. Read about writing software for flexibility, robustness and maintainability.

Let me tell you that what you wrote is very unpolite and even a bit aggressive.
As you know we all try to help each other in this board. The attitude from one member towards the others is expected to be polite, even friendly.
An attitude like the one you displayed, if meant, is not welcome.

Best regards
PGC

  • #10

Hi pcg,

I just want to point out that it’s Bryan Kelly who is being so rude, and not Hedges.

 

smr801

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

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

Необходимо создать массив констант в четыре строки и восемь столбцов, заполнить его значениями внутри скрипта VBA. Как это сделать правильно?

Код
Sub tst()
Dim arr_c(1 To 4) As Variant ' массив 1..4 массивов 0..7
Dim arr_d(1 To 4, 1 To 8) As Variant 'двумерный массив значений

arr_c(1) = Array("$AY$6:$CD$53", 0.9, "=стабилизация!R61C1:R150C1", "=стабилизация!R61C11:R150C11", 90, _
      "=стабилизация!R61C13:R150C13", "=стабилизация!R61C7:R150C7", "=стабилизация!R61C9:R150C9")
arr_c(2) = Array("$AY$6:$CL$53", 0.72, "=стабилизация!R61C1:R159C1", "=стабилизация!R61C11:R159C11", 99, _
       "=стабилизация!R61C13:R159C13", "=стабилизация!R61C7:R159C7", "=стабилизация!R61C9:R159C9")
arr_c(3) = Array("$AY$6:$CT$53", 0.6, "=стабилизация!R61C1:R168C1", "=стабилизация!R61C11:R168C11", 108, _
      "=стабилизация!R61C13:R168C13", "=стабилизация!R61C7:R168C7", "=стабилизация!R61C9:R168C9")
arr_c(4) = Array("$AY$6:$bv$53", 1#, "=стабилизация!R61C1:R141C1", "=стабилизация!R61C11:R141C11", 81, _
      "=стабилизация!R61C13:R141C13", "=стабилизация!R61C7:R141C7", "=стабилизация!R61C9:R141C9")
For i = 1 To 4: For j = 1 To 8: arr_d(i, j) = arr_c(i)(j - 1): Next: Next
End Sub

Т.е. как мне сразу получить готовый массив arr_d минуя костыли в виде промежуточного массива arr_c? Excel 2003.

  1. 10-30-2004, 05:54 AM


    #1

    Solved: Declare a Constant Array

    Hi,

    Can I declare an array in a similar fashion to a constant so that the data can be used by separate elements of a userform and sent to a function for processing. I don’t want to put them on the Userform itself, if I can avoid it.
    Something like the following
    [VBA] Cols = Array(«A», «D», «G», «H»)

    Sub Test1()
    ‘Cols = Array(«A», «D», «G», «H»)
    Range(Cols(0) & «3»).Select
    End Sub

    Sub test2()
    Dim Cols()
    ‘Cols = Array(«A», «D», «G», «H»)
    For Each gc In GetCols(Cols)
    msg = msg & gc & «, «
    Next
    MsgBox msg
    End Sub

    Function GetCols(Cols() As Variant) As Variant
    Dim MyCols()
    ReDim MyCols(UBound(Cols))

    For i = 0 To UBound(Cols)
    MyCols(i) = Range(Cols(i) & «:» & Cols(i)).Column()
    Next
    GetCols = MyCols

    End Function

    [/VBA]


  2. 10-30-2004, 01:02 PM


    #2

    Hi MD,

    I don’t believe that you can declare a Constant array.

    Possible alternatives:

    1. A Public array variable that you fill with a ‘starter’ routine.

    2. Store the data in a worksheet.


  3. 10-31-2004, 10:29 PM


    #3

    How about a public function that returns the array. Function works just like any variables.

    Try this.
    [vba]
    Public Function Arr()
    Arr = Array(«a», «b», «c»)
    End Function

    Sub try()
    For Each a In Arr
    MsgBox a
    Next a
    End Sub
    [/vba]


  4. 11-01-2004, 09:57 AM


    #4

    That’s pretty good Sixth Sense. If that were the method, as I sometimes find myself lacking options, you can add different qualifying lines to your code so you don’t have to keep writing multiple Public Functions. You can just call from the sub routine and assign them in your Function …

    [vba]Option Explicit
    Public Function Arr(test)
    Select Case test
    Case «yes»
    Arr = Array(«a», «b», «c»)
    Case «no»
    Arr = Array(«d», «e», «f»)
    End Select
    End Function

    Sub try()
    Dim a As Variant, test As String
    test = «no»
    For Each a In Arr(test)
    MsgBox a
    Next a
    End Sub[/vba]

    Change the ‘test = «no» ‘ to whatever you wanted, msgbox, returned value, whatever. Just thought I’d throw that out there, fwiw.


  5. 11-01-2004, 10:40 AM


    #5

    Hi,
    Thanks to all. I’ve decided to use the following, (which works on my test form at least!)
    MD
    [VBA]
    Function Arr(MySet As String)
    Select Case MySet
    Case Is = «A»
    Arr = Array(«A», «B», «C», «D»)
    Case Is = «B»
    Arr = Array(«E», «F», «G», «H»)
    Case Is = «C»
    Arr = Array(«I», «J», «K», «L»)
    End Select

    End Function
    Private Sub UserForm_Initialize()
    For Each A In Arr(«B»)
    ListBox1.AddItem A
    Next
    End Sub
    [/VBA]



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Можно ли в VBA создать массив констант?

От:

Titus

 
Дата:  08.07.04 10:56
Оценка:

Что-то вроде того:
Const cnstStr(1 to 3)={1,2,3}


Re: Можно ли в VBA создать массив констант?

От:

Vi2

Удмуртия

http://www.adem.ru
Дата:  12.07.04 04:18
Оценка:

1 (1)

Здравствуйте, Titus, Вы писали:

T>Что-то вроде того:

T>Const cnstStr(1 to 3)={1,2,3}

Такого нет, но есть эмуляция средствами Split.

Const cnstStrText As String = "1,2,3"
Dim cnstStr() As String

...
  cnstStr = Split(cnstStrText, ",")
  Debug.Print cnstStr(0),cnstStr(1),cnstStr(2)

Vita


Выше головы не прыгнешь, ниже земли не упадешь, дальше границы не убежишь! © КВН НГУ


Re[2]: Можно ли в VBA создать массив констант?

От:

EvilChild

Ниоткуда

 
Дата:  27.07.04 14:17
Оценка:

Здравствуйте, Vi2, Вы писали:

Vi2>

Vi2>Const cnstStrText As String = "1,2,3"
Vi2>Dim cnstStr() As String

Vi2>...
Vi2>  cnstStr = Split(cnstStrText, ",")
Vi2>  Debug.Print cnstStr(0),cnstStr(1),cnstStr(2)
Vi2>

А где здесь константность массива?


Re[2]: Можно ли в VBA создать массив констант?

От:

Bob Kotl

Россия

 
Дата:  19.09.04 11:47
Оценка:

Здравствуйте, Vi2, Вы писали:

Vi2>Здравствуйте, Titus, Вы писали:


T>>Что-то вроде того:

T>>Const cnstStr(1 to 3)={1,2,3}

Vi2>Такого нет, но есть эмуляция средствами Split.


Vi2>

Vi2>Const cnstStrText As String = "1,2,3"
Vi2>Dim cnstStr() As String

Vi2>...
Vi2>  cnstStr = Split(cnstStrText, ",")
Vi2>  Debug.Print cnstStr(0),cnstStr(1),cnstStr(2)
Vi2>


это класс, но вот если массив констант большой, то строка получается достаточно длинной. У меня произошла такая вещь: Word 2003 отказался создавать строку, состоящую более чем из 24 конкатенаций (строк, соединённых по _). То есть данный способ мне не подходит.
Нет ли в VBA аналога старому доброму оператору DATA, который был в GW-Basic’e (и в QBasic’e тоже, по-моему)?


Re: Можно ли в VBA создать массив констант?

От:

Andrew Merkulov

Россия

www.ibprovider.com
Дата:  01.10.04 11:33
Оценка:

Здравствуйте, Titus, Вы писали:

T>Что-то вроде того:

T>Const cnstStr(1 to 3)={1,2,3}

Хм. а enum не подойдет?
Что за необходимость то в массиве констант? Как вы их собираетесь применять?

… << RSDN@Home 1.1.3 stable >>

Подождите ...

Wait...

  • Переместить
  • Удалить
  • Выделить ветку

Пока на собственное сообщение не было ответов, его можно удалить.

Понравилась статья? Поделить с друзьями:
  • Excel vba задать границу ячеек
  • Excel vba добавить модуль
  • Excel vba задание переменной
  • Excel vba добавить дату
  • Excel vba для чего option explicit