如何使用VBA将以=开头的字符串插入单元格值?

时间:2018-12-22 14:36:17

标签: excel vba string excel-vba

我正在研究一个将各种类型的数据插入工作表(ws)的脚本。

Dim ws as Worksheet
Dim Index_Array(0 to 5) As Variant
Dim i as Integer

Set ws = ActiveSheet

Index_Array(0) = "This is some text."
Index_Array(1) = "This is also some text."
Index_Array(2) = "22004"
Index_Array(3) = 42
Index_Array(4) = 2.34657
Index_Array(5) = "=55"       'Yes, this should in fact be a string, not a formula or a number

For i = LBound(Index_Array) To UBound(Index_Array)
    ws.Cells(1, i + 1).Value = Index_Array(i)
Next i

问题是当我尝试将字符串=55插入单元格A5时,它给了我

  

运行时错误1004:应用程序定义或对象定义的错误。

除了在这种情况下之外,脚本都可以正常工作,我相信这是因为它正在尝试使其成为公式。我不想强迫所有内容都以'字符开头,因为并非所有内容都是字符串。有没有简单的方法可以使Excel接受以等号开头的字符串作为单元格值?

3 个答案:

答案 0 :(得分:5)

在每个数组项的前面添加一个',并使其在Excel UI中成为文本。

如此

Dim ws As Worksheet
Dim Index_Array(0 To 5) As Variant
Dim i As Integer

Set ws = ActiveSheet

Index_Array(0) = "This is some text."
Index_Array(1) = "This is also some text."
Index_Array(2) = "22004"
Index_Array(3) = 42
Index_Array(4) = 2.34657
Index_Array(5) = "=55"

For i = LBound(Index_Array) To UBound(Index_Array)
    ws.Cells(1, i + 1).value = "'" & Index_Array(i) ' add a "'" to make it a text value in excel UI
Next

答案 1 :(得分:1)

我认为正确的方法是从第一点开始将值转换为字符串。
第一种方式:

Index_Array(5) = "'=55"

Index_Array(5) = cstr("'=55")

如果您在定义数据时无法更改数据,并且仅希望这种情况发生在以=开头的数据上,请使用if与left(array(i),1) = "="并将"'"添加到第一个其中:

For i = LBound(Index_Array) To UBound(Index_Array)
    if left(array(i),1) = "=" then 
        ws.Cells(1, i + 1).value= "'"& array(i)
    else 
        ws.Cells(1, i + 1).value = array(i)
    end if
next i

致谢,
M

答案 2 :(得分:-1)

常规vs文本

当单元格中具有常规格式时:

For i = LBound(Index_Array) To UBound(Index_Array)
    If i = 5 Then
      ws.Cells(1, i + 1).NumberFormat = "@"
      ws.Cells(1, i + 1).Value = Index_Array(i)
     Else
      ws.Cells(1, i + 1).Value = "'" & Index_Array(i)
    End If
Next