ActiveCell.FormulaR1C1使用类型化字符串与可变字符串

时间:2020-07-05 19:46:26

标签: excel vba excel-formula

我正在尝试使用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

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

Sheet1

enter image description here

Sheet2工作不正常只会显示if语句

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试使用此备用代码

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,因为这可能会导致某些版本问题。