简体   繁体   English

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

[英]How do I Insert a String That Starts With = Into a Cell Value Using VBA?

I am working on a script that inserts various types of data into a worksheet (ws).我正在编写一个将各种类型的数据插入工作表 (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

The problem is when I try to insert the string =55 into cell A5, it gives me问题是当我尝试将字符串=55插入单元格 A5 时,它给了我

Run-time Error 1004: Application-defined or object-defined error.运行时错误 1004:应用程序定义或对象定义的错误。

The script is all working perfectly fine except in this case, and I believe it is because it is trying to make it a formula.除了在这种情况下,该脚本都工作得很好,我相信这是因为它试图使它成为一个公式。 I don't want to force everything to start with a ' character because not everything is a string.我不想强制所有内容都以'字符开头,因为并非所有内容都是字符串。 Is there an easy way to make Excel accept a string that starts with an equal sign as a cell value?有没有一种简单的方法可以让 Excel 接受以等号开头的字符串作为单元格值?

Adds a ' in front of each array item and makes it a text in the Excel UI.在每个数组项前添加一个 ' 并使其成为 Excel UI 中的文本。

so所以

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

I think the correct way is to turn your value to string from first point.我认为正确的方法是从第一点开始将您的值转换为字符串。
first way:第一种方式:

Index_Array(5) = "'=55"

or要么

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

if you can't change the data when defining it, and only you want this happens to your data starting with = , use an if with left(array(i),1) = "=" and add "'" to first of that:如果您在定义数据时无法更改数据,并且只希望以=开头的数据发生这种情况,请使用带有left(array(i),1) = "="的 if 并将"'"添加到第一个那:

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

Regards,问候,
M

General vs Text一般与文本

When you have the general format in the cells:当单元格中有通用格式时:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM