簡體   English   中英

如何使用 VBA 將以 = 開頭的字符串插入到單元格值中?

[英]How do I Insert a String That Starts With = Into a Cell Value Using 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 接受以等號開頭的字符串作為單元格值?

在每個數組項前添加一個 ' 並使其成為 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

我認為正確的方法是從第一點開始將您的值轉換為字符串。
第一種方式:

Index_Array(5) = "'=55"

要么

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

如果您在定義數據時無法更改數據,並且只希望以=開頭的數據發生這種情況,請使用帶有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

問候,

一般與文本

當單元格中有通用格式時:

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