如何在循环中获取特定的单元格范围?

时间:2016-11-21 14:09:55

标签: excel-vba vba excel

我如何重写它才能正确使用单元格公式?

For lineNum = 1 To UBound(reportArray, 2)
    With scanSheet
        .Cells(baseRow, 1) = reportArray(1, lineNum)
        .Cells(baseRow, 2) = reportArray(2, lineNum)
        .Cells(baseRow, 3).Formula = "=IF(LEN(B&baseRow)>3,TRIM(LEFT(TRIM(B&baseRow),2)),B&baseRow)"
        .Cells(baseRow, 4).Formula = "=IF(LEN(B&baseRow)>3,TRIM(RIGHT(TRIM(B&baseRow),2)),B&baseRow)"
    End With
    baseRow = baseRow + 1
Next lineNum

1 个答案:

答案 0 :(得分:0)

将公式的2行更改为下面的代码(假设baseRow的值为表示行号的数字):

  .Cells(baseRow, 3).Formula = "=IF(LEN(B" & baseRow & ")>3,TRIM(LEFT(TRIM(B" & baseRow & "),2)),B" & baseRow & ")"
  .Cells(baseRow, 4).Formula = "=IF(LEN(B" & baseRow & ")>3,TRIM(RIGHT(TRIM(B" & baseRow & "),2)),B" & baseRow & ")"

注意:将来使用“帮助”字符串。

Dim str As String
str = "=IF(LEN(B" & baseRow & ")>3,TRIM(LEFT(TRIM(B" & baseRow & "),2)),B" & baseRow & ")"
Debug.Print str

然后,您将在即时窗口中获得公式字符串:

=IF(LEN(B2)>3,TRIM(LEFT(TRIM(B2),2)),B2)