簡體   English   中英

在VBA中,相對於范圍編寫公式的語法是什么?

[英]In VBA, what is the syntax for writing a formula relative to a range?

在Excel中,我編寫了一個簡短的腳本,該腳本應刪除每個單元格開頭包含“ *”符號的第一個字符。 我到目前為止所擁有的是

Sub Macro5()

Dim Rng As Range
Dim i As Long
i = 1

While i <= 20000
Set Rng = Range("A" & i)

    If InStr(Rng, "*") > 0 Then
        Rng.Offset(0, 1).Formula = "=Right(Rng,LEN(Rng)-1)"
        i = i + 1
    Else: i = i + 1

End If
Wend
End Sub

調用腳本的行似乎有效,但是放入B列的公式是“ = Right(Rng,LEN(Rng)-1)”,它給出一個“名稱?”。 錯誤。 如何定義LEN公式以將Rng用作范圍,而不是電子表格上的“單詞”?

使用R1C1 type formulae可以使這種情況下的生活變得更加輕松。

Sub RemoveFirstStar()
    Dim rng As Range, c As Range

    Set rng = Range("A1:A2000")

    For Each c In rng.Cells
        If Left(c, 1) = "*" Then
            c.Offset(0, 1).FormulaR1C1 = "=mid(rc[-1],2,1000)"
        End If
    Next c
End Sub

對於您的特定代碼示例,請在IF后面更改行:

Rng.Offset(0, 1).FormulaR1C1 = "=Right(RC[-1],LEN(RC[-1])-1)"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM