San*_*per 3 string excel vba 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
Run Code Online (Sandbox Code Playgroud)
问题是当我尝试将字符串=55插入单元格A5时,它给了我
运行时错误1004:应用程序定义的错误或对象定义的错误.
除了在这种情况下,脚本完全正常工作,我相信这是因为它试图使它成为一个公式.我不想强迫一切都以一个'角色开始,因为并非一切都是一个字符串.有一种简单的方法可以让Excel接受以等号作为单元格值开头的字符串吗?
在每个数组项的前面添加一个',并在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
Run Code Online (Sandbox Code Playgroud)