【问题标题】:ActiveCell.FormulaR1C1 using a typed string vs variable stringActiveCell.FormulaR1C1 使用类型化字符串与变量字符串
【发布时间】:2020-10-25 23:03:03
【问题描述】:

我正在尝试使用 Sheet1 中的数据动态执行一个简单的 if 语句,并将结果放在 Sheet2 上。 excel if 语句是 =IF(Sheet1!C2:C35="Sold",Sheet1!A2:A35,"") 并且工作正常,除了它不是动态的。然后,我可以根据需要将声明复制到页面下方。我使用了录制宏功能,得到如下:

ActiveCell.FormulaR1C1 = "=IF(Sheet1!R[-1]C[-1]:R[32]C[-1]=""Sold"",Sheet1!R[-1]C[-3]:R[32]C[-3],"""")" and copied it down the page.  It also works fine.

问题是当我创建一个名为 BuySellRng 的字符串变量(作为字符串)并将相同的字符串与变量放入以使其动态时,它只返回不执行 if 语句的字符串。

Sub Macro13()
'
' Test Macro 
'
Dim ir As Long

Dim BuySellRng As String

Worksheets("Sheet1").Activate
ir = Range("C" & Rows.Count).End(xlUp).Row  'gets the number of rows which is the variable

'
BuySellRng = """=IF(Sheet1!R[-1]C[-1]:R[" & ir - 3 & "]C[-1]=" & """" & """" & "Sold" & """" & """" & ",Sheet1!R[-1]C[-3]:R[" & ir - 3 _
                        & "]C[-3]," & """" & """" & """" & """" & ")"""

'
    Sheets("Sheet2").Select
    Range("D3").Select
    ActiveCell.FormulaR1C1 = "=IF(Sheet1!R[-1]C[-1]:R[32]C[-1]=""Sold"",Sheet1!R[-1]C[-3]:R[32]C[-3],"""")"
' the above works
'    ActiveCell.FormulaR1C1 = BuySellRng   'this does not
    
    
    Range("D3").Select
    Selection.AutoFill Destination:=Range("D3:D34"), Type:=xlFillDefault
    Range("D3:D34").Select
End Sub

我会添加我的电子表格,但不知道如何添加。

表 1

Sheet2 Working not working 只显示 if 语句

【问题讨论】:

    标签: excel vba excel-formula


    【解决方案1】:

    试试这个替代代码

    Sub Macro13()
      Dim lLastRow As Long
      
      With ThisWorkbook.Sheets("Sheet1")
        lLastRow = .Cells(.Rows.Count, 3).End(xlUp).Row
      End With
    
      With ThisWorkbook.Sheets("Sheet2")
        With .Range("D2")
          .Formula = "=IF(Sheet1!C2=""Sold"",Sheet1!A2,"""")"
          .Copy
        End With
        .Range(.Range("D3"), .Range("D" & lLastRow)).PasteSpecial xlPasteFormulas    
      End With
      
      Application.CutCopyMode = False
    End Sub
    

    编辑:将.Formula2 更改为.Formula,因为这可能会导致一些版本问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 2019-06-08
      • 1970-01-01
      • 2011-06-01
      • 1970-01-01
      相关资源
      最近更新 更多