Excel vba const array

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.

  • Remove From My Forums
  • Question

  • Hi All,

    Does it possible to declare const string array like this:

    const MY_TABLE(2) AS String=ARRAY(«IN»,»TW»)

    • Edited by

      Monday, March 31, 2014 10:14 AM

Answers

  • Don’t think Array constants are supported by VBA.


    Happy to help ! When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answered

    • Proposed as answer by
      Michal Krzych
      Monday, March 31, 2014 4:22 PM
    • Marked as answer by
      Luna Zhang — MSFT
      Tuesday, April 8, 2014 9:27 AM

  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

Jul 24, 2009

Is it possible to use a contstant array in Excel VBA? I have tried several differnt ways to declare it, but the VBA editor keeps yelling at me. The following did not work:

View 2 Replies

ADVERTISEMENT

Extend A Constant Array

Jul 30, 2008

I’ve never had to venture into Arrays as there was no need.

I’m now faced with Arrays.

Generally I’m able to figure things out, in this case I’m stumped.

What I have is a Constant Array, that output the amount of Rows the Array displayed in.

I know the information is there, what I don’t know is how to extend the rows.

ie it Outputs 5 Rows right now, with a top row header.

What I want is 10 rows with a header.

View 9 Replies
View Related

Array Constant Named Ranges

Jul 17, 2008

Is it possible to make an named array constant from named constants to use in a lookup?

Eg

I have defined the following constants in Names:

Text1 = «AAAAAAAAAA»
Text2 = «BBBBBBBBBBB»
Num1 = «1234567890»
Num2 = «0987654321»

And would like to make the following array constant in Names:

Arr = {Text1,Num1;Text2,Num2}

However, it does not work.

I am using Excel 2007 by the way and the above values are made up.

View 9 Replies
View Related

Array Constant From Cell Values

Aug 26, 2008

I need to convert a cell that has a list of values A1 = 1,2,3. To a range expression {1;2;3}. I want to do this with a formula and not VBA. Example: Cell D1 has the formula = SUMPRODUCT(COUNTIF(C30:C31,A30:A32),B30:B32). I want to put the list range from column C into one cell.

ABCD
110140
2203
3305
450
560

View 4 Replies
View Related

Replace A Constant With A Variable In An Array Formula.

Oct 1, 2007

I have the following array function that I am trying to get to work properly:

ActiveCell.FormulaArray = «=SUM(IF(NCR!O2:O100=39326,NCR!Q2:Q100,0))»
39326 is the value of 9/1/2007, and this formula works properly.

I am looking for a way to use this formula but replace 39326 with whatever date is in the first row of the same column as the active cell when it is run.

That is, if the macro was run with cell B8 as the active cell, «39326» would be replaced with whatever value was in cell B1.

View 9 Replies
View Related

Array Constant Composed Of Named Constants

Jun 20, 2008

I try to understand what the syntax is to create and use an array named constant which would be composed of other constant.

Example :
Constant called AvgZone1 which is =AVERAGE(zone1)
Constant called AvgZone2 which is =AVERAGE(zone2)

and then create a named array constant based on the names : =AvgZone1,AvgZone2
is not working. You cannot for example do a SUM().

View 9 Replies
View Related

Constant Variables — Declare Name In Separate UserForm As Constant

May 8, 2012

I have a userForm (Form1) that contains a persons name that I would like to reference in a separate UserForm (Form2). In the separate UserForm (Form2) I need to reference this persons name many times, so I was wondering if there was a was to declare this name in the separate UserForm (Form2) as a constant. Only thing is that a constant, to the best of my knowledge, must be an expression and not a variable. Mainly, I’m trying to avoid declaring the myName variable in each Sub within Form2, which it will be needed for a ton of Sub’s.

Code for Form2: Const myName As String = Form1.txtName.Value

View 5 Replies
View Related

If And Constant Logical

Jun 17, 2008

i have problem with a long code.

So I divided that code in 4 parts.

So I have
module1 -> Sub Macro1()
module2 -> Sub Macro2()
module3 -> Sub Macro3()
module4 -> Sub Macro4()

I have declared

Option Explicit

Dim mdNextTime1 As Double
Dim myEnter As Integer
‘Dim myK1 As Integer
‘Dim myK2 As Integer
‘Dim myK3 As Integer
Dim myK4 As Integer
Const myC As Integer = 82
Dim Lastrow As Integer
Dim myActualRow As Integer

all my sub have the following structure:

View 9 Replies
View Related

Declare Constant

May 15, 2007

what does the symbol # means in VBA? (but I couldn’t put the # in the subject of my message )

I’m trying to understand someone’s code… at some point he wrote:
sum_LU_Area = 0#

I thought that the # was used to declare a constant but I’m not too sure because in his code earlier he declared
Public sum_LU_Area As Double

Beside, sum_LU_Area is calculated somewhere further in the program.

View 7 Replies
View Related

Increment One Column But Keep The Other Constant

Jun 28, 2009

Here is what I try to do:
At
A1 = Power(C1,B1)
A2 = Power(C2, B1)
A3 = Power(C3, B1)
….
An = Power(Cn, B1)

How can I increment column C while keeping B constant at B1 by using right-bottom mouse pointer dragging on column A? Or is there another way?

View 2 Replies
View Related

Copy Formula With 1 Constant Value?

Oct 6, 2011

If I have a formula that I want to copy throughout a column, but I want to keep one of the parts of the formula constant, is there a short way to do this?

For example:

First cell is A1*O24
Second Cell is A2*O24
Third Cell is A3*O24

Right now when I try to copy the formulas, the second cell always reverts to A2*O25, which is not correct.

View 2 Replies
View Related

Using Variable Instead Of Constant In VBA Formula

Jan 8, 2012

I try to adjust chart range using variable value instead of constant value.

My current code :
ActiveSheet.ChartObjects(«Chart 4»).Activate
ActiveChart.SeriesCollection(1).Values = «=’Check_2G’!$Z$2:$Z$32»

I need to make range ( «=’Check_2G’!$Z$2:$Z$32» ) adjestable with varible like m instead of 32 in previous code.

View 2 Replies
View Related

Macro Is Counting A Constant Twice?

Apr 25, 2012

For a single column of values, the following macro counts the first value twice, how can i fix this? for example: A1 thru A5 are a,a,b,c,d the result is

a 2
a 2
b 1
c 1
d 1

and should be
a 2
b 1
c 1
d 1

Macro:

Sub CountOfEachItem()
Dim ListRange As Range
Dim NewList As Range

[Code]…..

View 1 Replies
View Related

Excel VBA — Using Constant For A Set Of Values

Oct 19, 2012

Code:
Const Books1 = Array(«5638», «5639», «10984»)
Const Books2 = Array(«3140», «7509», «3050», «7549», «7508», «7032», «6770», «6773», «4388», «6460»)

I want to set an array as above for multiple use in my code (Used for auto-filtering various data with the same criteria).

The above is not allowed it seems, is there an alternative method so that if my Constant changes I only need to amend this once.

View 6 Replies
View Related

Create A Constant Variable

Apr 14, 2009

I want to basically set a varible that can be called back into a multiple of documents I will try and explain this as best as I can but it is a fortnightly pay date… i.e. 22/04/2009 Wednesday… as the payroll is fortnightly I want to be able to use the current date or todays date in a future proof macro.

i.e. if todays date is the 14/04/09 then the next pay date has to be the 22/04/09, if this was run in two weeks it would be 06/05/2009.

I was thinking a long the lines of lock in one start date… 14/01/09, then adding increments of 14 days until todays date — variable + 14 * r = «-«

View 9 Replies
View Related

One Constant To Multiple Cells

Jun 4, 2009

I am just wondering if this can be possible:

this is an table with a lot of cells

12 36 89 56 97 78 98 36
36 89 56 97 78 98 36 12
97 78 98 36 56 97 78 98
12 36 89 56 97 etc ..
etc…

to become like this …

View 9 Replies
View Related

Refer To Named Constant In VBA

Oct 1, 2007

I created a name in Excel 2002, Name = «NameToUse», Refers to = «Bill».
How do I get the value in VBA code?

Range(«NameToUse»).value ‘ doesnt work
NameToUse ‘ doesn’t work

View 3 Replies
View Related

Ambiguous Name Detected With Constant

Oct 24, 2007

Option Explicit
Public Const ARK As String = «Inddata-ARK»
Public Const VVS As String = «Inddata-VVS»
Public Const KON As String = «Inddata-KON»
Public Const EL As String = «Inddata-EL»
Public Const LD As String = «Inddata-LD»
Public Const K�L As String = «Inddata-K�L»
Public Const OpDat As String = «Opdatering»

And then macro’s under it… So the aboce is in module «INIT_S». Now in another module «RUN_P» I have a sub-rutine that uses these constants with a select case.
Likes this:

Sub OpEksInitNu()
Select Case ActiveSheet. Name
Case ARK
With OpEks
‘more stuff
Case VVS
‘more stuff
Case KON
‘more stuff
End Sub

But when I try to run OpEksInitNu i comes with ambigious name with ARK as the error, later down I use another public constant. But i keep getting the ambigious name error.. What could cause that… I have tried to locate all ARK, VVS etc. to try to determine if it is used later on, but it’s not! I only declare the constants one time, and no module is called ARK, VVS etc.

View 2 Replies
View Related

Define Constant Last Row For Module

Feb 4, 2008

I’m looking to run several subs in a module which all refer to the same constant but I’m having difficulty defining that constant in a way that the various subs will accept. Basically I’m trying to define a constant LastRow. I am fairly new to VBA so am not sure whether to use a Get LastRow public property (which I tried to use and failed) or a Function and then how to make this readable by all the subs.

View 5 Replies
View Related

Subtracting Monthly Sales From Constant?

Dec 12, 2013

I have sales per month going down a column and I would like to subtract a corresponding $ amount going across columns. It’s hard to explain but I would like a formula that I can populate all of the cells with. Spreadsheet should make it clearer.

View 6 Replies
View Related

Making A Constant And A Variable In 2007

Nov 18, 2008

assume we have constant P = 100, K=50 and F=10.

I would like to «lock» these cells, and have a variable which could adjust and this variable would multiplicate each one and put out the number.

For example:

P = 100
K = 50
F = 10

Variable: 10 this would generate a sum of:

P = 1000
K = 50
F = 10

View 3 Replies
View Related

Constant Errors When Referencing Another Sheet?

Nov 5, 2013

Ok, I have a spreadsheet that I use to track the majority of my work throughout the day. I have about 10 columns that I use for my own information, and about 4 of them that my colleagues need updates on. I have one sheet «worktracking» and another sheet «printable.» Printable has just the 4 columns of info that my colleagues might need, formatted in a way that prints out nicely. Each column in «printable» references a column in «work tracking» like this

=’worktracking’!c2

Now the problem that I’m running into is that I routinely delete rows from the «worktracking» sheet, which results in a reference error on the «printable» sheet. I am wondering if there is a way to rework it, such that when I delete a row from «worktracking,» then «printable» just does the same, and only retains rows that have data in them…

View 3 Replies
View Related

Moving Data Based On Constant

Oct 8, 2011

I have a list of data which which has repeated supplier numbers in column A. For instance

A123
A123
A123
X456
x456
x456
x456

The information in other 13 columns is variable and I need to be able to move all the rows which start with the first supplier number to another sheet which I will rename to that name, then move the second set of supplier numbers to a second sheet etc. So in my above mini example I would have one sheet named A123 with 3 rows of data and another sheet named X456 with 4 rows of data.

The number of supplier codes will be different every day and the number of rows within each supplier number will also vary. Each new datafile that comes in daily creates a new file do I do not have to worry about existing values only what the current file contains. I have used the following code to move data based on a known constant before but dont know how to tell the macro «move all the data while the value stays the same»

Sub DiffOrderNo()
Dim totalrows As Long, row As Long
Cells.Sort Key1:=Range(«A1»)
totalrows = ActiveSheet.UsedRange.Rows.Count

[Code] ………..

View 3 Replies
View Related

Identify Min And Max In Constant Dynamic Range

Sep 13, 2012

I need to calculate a formula in a constantly changing range. In the example below, the formula in column C would yield the % change in column A between the first «P» value in column B and the minimum value prior to the next «P» value.

So, the first result would be =(A2-A1)/A1, which is (1896.3274 — 1973.4764)/1973.4764. The cells in column C would be blank until the next formula, which is =(A8-A7)/A7, then it gets tricky. The next would be =(A14-A10)/A10.

A B C
1 1973.4764 P
2 1896.3274
3 1922.5499
4 1905.2061
5 1985.6797

[Code] ………..

View 7 Replies
View Related

Declare Private Constant As Long?

Dec 27, 2012

I am trying to declare lngLr as Long and Constant. But it’s buggin out on me. Is this the correct way to do it?

Code:
Private Const lngLr As Long = «.Cells(Rows.Count, 1).End(xlUp).Row»
Sub calculate_active_employees_sheet_years_of_service_w_Oasis()
Application.ScreenUpdating = True

[Code]…..

View 4 Replies
View Related

Error / Constant Expression Required

Jan 22, 2013

I am getting ‘Constant Expression Required’ and this line of code highlighted.

Code:
Const sFile As String = ThisWorkbook.Path & «Survey.xlsm»

View 5 Replies
View Related

Replace Constant Value With Variable In R1C1 VBA

Mar 15, 2013

My current dataset goes to row 256, when I use the Macro Recorder it produces the following «static» code.

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
«claim_export!R1C1:R256C23», Version:=xlPivotTableVersion12). _
CreatePivotTable TableDestination:=»Sheet5!R3C1″, TableName:=»PivotTable1″ _
, DefaultVersion:=xlPivotTableVersion12

QUESTION/PROBLEM:

Each month the amount of rows could be different (columns should be the same)… I have tried (3) different ways to replace the 256 with my variable name called «numbers»

SourceData:=»claim_export!R1C1:R » & numbers & «C23» OR
SourceData:=»claim_export!R1C1:R[» & numbers & «]C[23]» OR
SourceData:=»claim_export!R1C1:R[» & numbers & «]C23

They all produce the same resulting error:

Run-time error ‘5’: Invalid procedure call or argument.

Note* I am sure my variable is working, because when I «step into» (F8) my code and hover over my variable I can see it showing the number I expect.

View 1 Replies
View Related

Use Same User-defined Constant In 2 Enum

May 11, 2013

I found out that using Enum one can have a dropdown box to choose from when inserting a parameter in a function.

But how can I have the same user-defined constant in more then one Enum? It works with standard VBA variables like vbEmpty, so why not with self made constants?

I tried this which gives the error: Ambiguous name detected

Code:
Private Const vbTest = 99 »’ = Ambiguous name detected !!!
Enum eTest1 »’gives 3 choices
vbEmpty »’ = standard VBA 1
vbLong »’ = standard VBA 3
vbTest »’ not in VBA, so I would assign 99 to it
End Enum

[Code] …..

View 1 Replies
View Related

Subtracting Various Cells From One Constant Cell?

May 15, 2014

Say I have the number 325 in A1. Each time I type a number in A2, B2, C2, D2, E2, A3, B3, etc… I would like the number (325) in A1 to be reduced.

Also, how do I create a pull down list?

View 6 Replies
View Related

Multiple Variables To Equal Constant

Mar 11, 2007

I’m trying to create a spreadsheet that will tell the user how much of two products to use in order to get a desired percentage of total fat. For example: if the total pounds is to be 3000 at a fat percentage of 30%. There would be two products (a lean meat and high fat meat). The percentage of fat in those two meats will change each time. The user will enter those percentages and then the formula needs to tell how many lbs of each to use in order to get the desired percentage of fat.

Each time there is a «target» amount of each product to use. For example: 1000 lbs of Lean Meant and 2000 lbs of Fat meat. Those are based on the ideal levels of fat in each.

However, sometimes the fat is not at the ideal so the formula has to be adjusted in order to compensate.

View 9 Replies
View Related

Может ли массив быть объявлен константой?

возможно ли либо:

  1. объявить массив как константа

    или

  2. использовать обходной путь для объявления массива, защищенного от добавления, удаления или изменения элементов и, следовательно, функционально постоянного в течение жизни макроса?

конечно, я мог бы это сделать:

Const myConstant1 As Integer = 2
Const myConstant2 As Integer = 13
Const myConstant3 As Integer = 17
Const myConstant4 ...and so on

…но он теряет элегантность работы с массивами. Я также могу загрузить константы в массив и перезагружать их каждый раз, когда я их использую, но любая неспособность перезагрузить массив с этими постоянными значениями перед использованием может подвергнуть код «постоянному» значению, которое изменилось.

любой работоспособный ответ приветствуется, но идеальным ответом является тот, который может быть настроен один раз и не требует каких-либо изменений/обслуживания при изменении другого кода.

6 ответов


вы можете использовать функцию для возврата массива и использовать функцию в качестве массива.

Function ContantArray()
    ContantArray = Array(2, 13, 17)
End Function

enter image description here

enter image description here


Как насчет того, чтобы сделать его функцией? Например:

Public Function myConstant(ByVal idx As Integer) As Integer
    myConstant = Array(2, 13, 17, 23)(idx - 1)
End Function

Sub Test()
    Debug.Print myConstant(1)
    Debug.Print myConstant(2)
    Debug.Print myConstant(3)
    Debug.Print myConstant(4)
End Sub

никто не может изменить его, изменить его размер или изменить его содержимое… Кроме того, вы можете определить свои константы на одной строке!


заявил String постоянная "1,2,3,4,5" и затем использовать Split создать новый массив, например так:

Public Const myArray = "1,2,3,4,5"

Public Sub createArray()

        Dim i As Integer
        A = Split(myArray, ",")

        For i = LBound(A) To UBound(A)
                Debug.Print A(i)
        Next i

End Sub

когда я пытался использовать ReDim или ReDim Preserve on A он мне не позволил. Недостатком этого метода является то, что вы все равно можете редактировать значения массива, даже если вы не можете изменить размер.


можно ли объявить массив константой? Нет.

обходные пути-самый простой, который я могу придумать, это определить константу с delim, а затем использовать Split функция для создания массива.

Const myConstant = "2,13,17"

Sub Test()
    i = Split(myConstant, ",")

    For j = LBound(i) To UBound(i)
        Debug.Print i(j)
    Next
End Sub


Если конкретной средой VBA является Excel-VBA, то хороший синтаксис доступен из метода оценки приложения Excel, который можно сократить до квадратных скобок.

смотреть на это

Sub XlSerialization1()
    Dim v
    v = [{1,2;"foo",4.5}]

    Debug.Assert v(1, 1) = 1
    Debug.Assert v(1, 2) = 2
    Debug.Assert v(2, 1) = "foo"
    Debug.Assert v(2, 2) = 4.5

    '* write all cells in one line
    Sheet1.Cells(1, 1).Resize(2, 2).Value2 = v
End Sub

Like this post? Please share to your friends:
  • Excel vba commandbar controls
  • Excel vba combobox1 list
  • Excel vba combobox ячейка
  • Excel vba combobox список значений
  • Excel vba combobox очистить список