如何在 VBA 中创建矢量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24327225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create a vector in VBA?
提问by RiMa
I have a small issue where I need to create a vector in EXCEL VBA
.
我有一个小问题,我需要在EXCEL VBA
.
I have the following scenario
我有以下场景
str=Sheets("Indata").Range("$C")
Vector= str
For example if the cell in C12
is 11 I want the following output:
例如,如果单元格C12
是 11 我想要以下输出:
Vector= "1 2 3 4 5 6 7 8 9 10 11"
回答by Ioannis
NUMBERS
数字
Sub test()
Dim str As String
str = Join(Application.Transpose(Evaluate("ROW(A1:A" & Range("C12").Value2 & ")")), " ")
Debug.Print str
End Sub
LETTERS
信件
Sub test2()
Dim str As String, varr, lCnt As Long
varr = Application.Transpose(Evaluate("64 + ROW(A1:A" & Range("C12").Value2 & ")"))
For lCnt = LBound(varr, 1) To UBound(varr, 1)
str = str & " " & Chr(CLng(varr(lCnt)))
Next lCnt
Debug.Print str
End Sub
UPDATE
更新
Loop avoider for LETTERS:
LETTERS 的循环避免器:
Sub test3()
Dim str As String
Const ALPHABET = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
str = IIf(CLng(Range("C12").Value2) <= 26, _
Mid(ALPHABET, 1, 1 + (2 *CLng(Range("C12").Value2 - 1))), "Error")
Debug.Print str
End Sub
You did not specify what happens if the value exceeds the last letter, so I throw an error. Is this what you want?
你没有指定如果值超过最后一个字母会发生什么,所以我抛出了一个错误。这是你想要的吗?
回答by Gary's Student
Consider:
考虑:
Public Function Vector(rIn As Range) As String
Dim N As Long
N = rIn(1).Value
Vector = "1"
For i = 2 To N
Vector = Vector & " " & i
Next i
End Function
EDIT#1:
编辑#1:
To get a lettervector, use:
要获得字母向量,请使用:
Public Function VectorA(rIn As Range) As String
Dim N As Long
N = rIn(1).Value
VectorA = "A"
For i = 2 To N
VectorA = VectorA & " " & Chr(64 + i)
Next i
End Function
回答by RiMa
-------SOLUTION-----------
- - - -解决方案 - - - - - -
Here is the solution to the problem above:
下面是上述问题的解决方案:
Dim N As Long
N = Sheets("Indata").Range("$C").Value
vector = "1"
For i = 2 To N
vector = vector & " " & i
Next i
What it does is that it gets a value say 11 from Sheets("Indata").Range("$C$12").Valueand returns a vector of:
它的作用是从Sheets("Indata").Range("$C$12").Value获取一个值,比如 11,并返回一个向量:
vector="1 2 3 4 5 6 7 8 9 10 11"
----Code to use letters instead of numbers-----
----使用字母代替数字的代码-----
Dim M As Long, vectorA As String
M = Sheets("Indata").Range("$C$13").Value
vectorA = Join(Evaluate("transpose(char(row(65:" & M + 64 & ")))"))
Dim M As Long,vectorA As String
M = Sheets("Indata").Range("$C$13").Value
vectorA = Join(Evaluate("transpose(char(row(65:" & M + 64 & ")))"))
What it does is that it gets a value say 11 from Sheets("Indata").Range("$C$13").Valueand returns a vector of:
它的作用是从Sheets("Indata").Range("$C$13").Value获取一个值,比如 11,并返回一个向量:
vector="A B C D E F G H I J K"