如何在vba中使用字符串作为变量?

时间:2016-06-14 17:20:59

标签: vba excel-vba excel

这就是我的细胞的样子:

enter image description here

这是我的代码,我将在下面解释。

Sub Macro1()
Dim product as String
Dim group as Long
Dim recordno as Long
dim pol_number as Long
dim plan_name as Long

product = "corp"
group = 1
recordno = 1
pol_number = 1
plan_name = "TTT"

Range("A2").Select
For i = 1 to 5
    ActiveCell.Value = Selection.End(xlUp).Value
    ActiveCell.Offset(0,1).Select
Next i

End Sub

我想用变量值填充所有单元格。我理解变量不区分大小写,我理解我所拥有的代码只是用列中最上面的单元格中的文本填充单元格,但我不知道是否有一个函数可以接受文本顶部单元格并将其转换为变量。这可能吗?

4 个答案:

答案 0 :(得分:2)

尝试从变量转到单元格

Dim values as Variant   
'Array 0 to 4
values = Array(product,group,recordno,pol_number,plan_name)    
Range("A2").Resize(1,5).Value2 = values

相反的是

Dim values as Variant
'Array 1 to 5
values = Range("A2").Resize(1,5).Value2 
product = values(1,1)
group = values(1,2)
recordno = values(1,3)
pol_number = values(1,4)
plan_name = values(1,5)

答案 1 :(得分:1)

如果您执行类似

的操作
someCell.Value = someOtherCell.Value

someOtherCell.Value"product",然后someCell将不会填充您在变量product中保存但"product"已保存的内容(我包含了引号强调这是一个字符串)。这是一件好事,因为如果你不小心在代码中输入了一些随机变量的名称,它会弄乱你的代码。

如果您的要求是这样的:

  • 您在PRODUCT等下面的行中写下了PRODUCT等的值。

  • 标题的顺序并不总是一样。

  • 您可能希望以后添加新变量而不必过于烦恼。

他们的某些键控列表可能就是你要找的东西。这意味着,不是通过数字索引引用变量,而是可以使用名称引用它们。

如果订单是固定的,你可能最好只使用数据,其中第1项是产品名称,第2项是组号等,如ja72和Sgdva建议。

但是,如果您仍想按名称引用变量,则可以使用集合:

Dim coll As New Collection
With coll
    .Add "corp", "product"
    .Add 1, "group"
    .Add 1, "recordno"
    '...
End With

然后,不是选择单元格并引用ActiveCell,而是应该直接引用单元格(使用选择,大多数情况下可以避免使用ActiveCell并减慢宏,甚至可能导致不必要的错误)

For i = 1 To 5
    Cells(2, i).value = coll(Cells(1, i).value)
Next i

集合的替代方法是一个字典,它提供了一种检查密钥是否存在的简单方法(使用集合来捕获错误)

Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
With dict
    .Add "product", "corp"
    .Add "group", 1
    .Add "recordno", 1
    '...
End With

现在您可以先检查条目是否存在,这样就不会产生错误:

For i = 1 To 5
    If dict.Exists(LCase(Cells(1, i).value)) Then 'note that the dictionary keys are case sensitive
        Cells(2, i).value = dict(LCase(Cells(1, i).value))
    Else
        MsgBox "Entry for " & LCase(Cells(1, i).value) & " not found!"
    End If
Next i

请注意,当您使用dict("somekey")且条目"somekey"不存在时,它不会引发错误但会添加空条目。

答案 2 :(得分:1)

为什么不是数组然后根据需要循环遍历元素?

Dim ArrayTitles() As Variant 'since strings and numbers are mixed
ReDim Preserve ArrayTitles(5)
ArrayTitles(1) = "corp"
ArrayTitles(2) = 1
ArrayTitles(3) = 1
ArrayTitles(4) = 1
ArrayTitles(5) = "TTT"

Range("A2").Select
For i = 1 To 5
MsgBox (ArrayTitles(i))

答案 3 :(得分:0)

我在想,你想要实现的目标可以通过这种方式解决

for j = 1 to 6 'Or whatever your last column happens to be
    if UCase(cells(1, j)) = "PRODUCT" then
        if ActiveCell.Column = j then
            ActiveCell.Value = "corp"
        end if
    end if
next j

那样的东西?

相关问题