所以我有这样的事情:
A B C ...
1 11 12 13
2 10 20 15
3 1 -8 -2
...
因此,A3
,B3
和C3
是通过将A1
减去A2
来生成的。
如果查看工作表的顶部,会有一个很长的公式栏,当您单击一个单元格时,它会显示单元格的公式。如果您手动填写工作表,则可以在该栏中输入= A1 - A2
之类的内容,并为您填写A3
。
就我而言,我在代码中使用.Formula = "IFERROR(A1 - A2, ""N/A""")
。
我遇到的问题是,当生成工作表时,而不是上面显示的所需输出,它显示的内容
A B C ...
1 11 12 13
2 10 20 15
3 #NAME? #NAME? #NAME?
...
如果单击单元格,公式栏实际显示它应用了正确的公式,如果我在单击公式栏后按Enter键,则会显示正确的数字。所以我就像手动输入公式一样。
这是我的代码。 ConvertToLetter()接受一个整数并转换为列字符。
Public Function ProcessExcelRpt(dataArray(,) As Object) As Integer
Dim ws As Worksheet
Dim r As Range
Try
For i As Integer = 1 To xlWorkBook.Sheets.Count
ws = xlWorkBook.Sheets(i)
r = ws.Range("A8")
ws.Range("A8").Resize(dataArray.GetUpperBound(0) + 1, dataArray.GetUpperBound(1) + 1).Value2 = dataArray
ws.Range("A2").Value2 = ws.Range("A2").Value2.ToString() & FormatDate(ReportDate, "MMMM dd, yyyy")
FormatColumns(ws, 8, dataArray.GetUpperBound(0) + 8)
excel.CalculateFull()
xlWorkBook.SaveAs(saveAs)
Exit For
Next
Catch ex As Exception
Return -1
End Try
Return 0
End Function
Public Sub FormatColumns(ws As Worksheet, ByVal firstRow As Integer, ByVal lastRow As Integer)
Dim rng As Range
Try
Dim colCnt, rowCnt, i As Integer
i = 0
For rowCnt = firstRow To lastRow
Dim row1, row2 As Integer
row1 = rowCnt - 2 ' go back 2 rows
row2 = rowCnt - 1 ' go back 1 row
' Apply formula to each cell in each row
For colCnt = 1 To 3
rng = ws.Range(ConvertToLetter(colCnt) & rowCnt) ' A1 for ex
rng.Formula = "=IFERROR(" & ConvertToLetter(colCnt) & row1 & "-" & ConvertToLetter(colCnt) & row2 & ", ""N/A"")"
Next
Next
Catch ex As Exception
End Try
End Sub
答案 0 :(得分:1)
如果您将其作为Sub
运行,那么它对我有用:
Sub foo(firstRow, lastRow)
Dim rng As Range
For rowCnt = firstRow To lastRow
Dim row1, row2 As Integer
row1 = rowCnt - 2 ' go back 2 rows
row2 = rowCnt - 1 ' go back 1 row
' Apply formula to each cell in each row
For colCnt = 1 To 3
Set rng = Cells(rowCnt, colCnt) ' A1 for ex
rng.Formula = "=IFERROR(" & Cells(row1, colCnt).Address & "-" & Cells(row2, colCnt).Address & ", ""N/A"")"
Next
Next
End Sub
如果您尝试从作为UDF的Function
调用执行此操作,它将无法正常工作,因为UDF可以在工作表上操作的明确限制,特别是您不能:
更改另一个单元格的值。