![](/img/trans.png)
[英]Efficiently assign cell properties from an Excel Range to an array in VBA / VB.NET
[英]Unable to assign formula to cell range in Excel
項目中的其他人的代碼,我正在努力修復。
listO.Range(i, j).FormulaR1C1 = FormulaMatrix(i, j)
其中FormulaMatrix(i, j)
始終是String
值。 無論隨機/測試值是什么,我嘗試使用,成功分配,除非它是一個公式,例如。
=IF(LENGTH([@Units])>0;[@SalesAmount]-[@DiscountAmount]0)
如果我刪除公式開頭的=
符號,它會被正確分配,但是它沒用,因為它不是公式。
@Units
, @SalesAmount
, @DiscountAmount
是列的引用/名稱。
因此,在分配公式時,我得到一個異常HRESULT: 0x800A03EC
。 我抬頭看了這個答案 ,以便得到解釋並遵循那里的一些指示。 我確定我的問題如下:問題是由於在單元格中輸入的函數而發生的,並且它正在嘗試更新另一個單元格。
檢查了這篇文章。 我嘗試了很多不同(比如只用公式而不是=
然后再次運行並放上等號),但同樣的問題。
我對如何處理這個問題一無所知。
.formulalocal
作品! (雖然.formula
, .value
和.formular1c1
沒有。)
我剛剛開始使用VB.NET並遇到了一個非常類似的問題。 這是我最初的簡化數據( Sheet1
Table1
):
然后在應用下面的代碼后我得到了這個:
表格的整個代碼:
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
'~~> Define your Excel Objects
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim strAddress As String = "C:\Temp\SampleNew.xlsx"
Dim list1 As Object
Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click
'~~> Add a New Workbook (IGNORING THE TWO DOT RULE)
xlWorkBook = xlApp.Workbooks.Open(strAddress)
'~~> Display Excel
xlApp.Visible = True
'~~> Set the relevant sheet that we want to work with
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
With xlWorkSheet
'~~> Change the range into a tabular format
list1 = .ListObjects("Table1")
End With
list1.range(2, 4).formulalocal = "=IF(LEN([@Month])>5;[@Income]-[@MoneySpent];0)"
'~~> Save the file
xlApp.DisplayAlerts = False
xlWorkBook.SaveAs(Filename:=strAddress, FileFormat:=51)
xlApp.DisplayAlerts = True
'~~> Close the File
xlWorkBook.Close()
'~~> Quit the Excel Application
xlApp.Quit()
'~~> Clean Up
releaseObject(xlApp)
releaseObject(xlWorkBook)
End Sub
'~~> Release the objects
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
@Siddharth Rout幫助制作了這段代碼,因為他擁有這個很棒的網站: http : //www.siddharthrout.com/
錯誤可能來自您當前的數據,分別是工作表的布局。 我建議你在分配公式之前檢查listO.Range(i, j).FormulaR1C1
的內容。
我有一個案例,其中范圍已經有錯誤的數據里面,然后奇怪的是,我不知道為什么,我不能分配新的公式。
如果是這種情況 - 嘗試清除范圍的值,然后分配公式:
listO.Range(i, j).FormulaR1C1 = ""
listO.Range(i, j).FormulaR1C1 = FormulaMatrix(i, j)
問題可能出在你的公式上。 試試這個-
=IF(LEN([@Units])>0,[@SalesAmount]-[@DiscountAmount],0)
如果這不起作用,我會嘗試使用.formula方法而不是.formulaR1C1 ..特別是你有沒有理由使用R1C1引用?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.