我正在尝试使用excel互操作在vb.net中打开一个excel文件 然后将一个公式添加到F2然后另存为exs为csv
有人能指出我如何连接'当我写'时,用公式cs中的数字Visual Studio将其视为注释而不是公式
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim newFileName As String = "Libanpost" + Date.Today.ToString("ddMMyyyy") + ".csv"
Dim oExcelFile As Object
Try
oExcelFile = GetObject("c:\database", "Excel.Application")
Catch
oExcelFile = CreateObject("Excel.Application")
End Try
oExcelFile.Visible = True
Dim strfilename As String = "Libanpost" + Date.Today.ToString("ddMMyyyy") + ".xls"
Dim strFolderPath As String = "c:\database"
oExcelFile.Workbooks.Open(strFolderPath + "\" + strfilename)
Dim oExcelsheet As Excel.Worksheet
oExcelsheet = oExcelFile.sheets("table1")
oExcelsheet.Range("f1").Value = "CRC"
oExcelsheet.Range("f2").Formula = " = IF(LEN(A2)=2,(CONCATENATE("'00000",A2)),IF(LEN(A2)=3,CONCATENATE("'0000",A2),IF(LEN(A2)=4,CONCATENATE("'000",A2),IF(LEN(A2)=5,CONCATENATE("'00",A2),IF(LEN(A2)=6,CONCATENATE("'0",A2),A2)))))"
oExcelFile.DisplayAlerts = False
oExcelFile.ActiveWorkbook.SaveAs(Filename:=strFolderPath + "\" + newFileName, FileFormat:=Excel.XlFileFormat.xlCSV, CreateBackup:=False)
oExcelFile.ActiveWorkbook.Close(SaveChanges:=False)
Dim file_count As Integer = File.ReadAllLines(strFolderPath + "\" + newFileName).Length
MsgBox(file_count)
oExcelFile.DisplayAlerts = True
oExcelFile.Quit()
oExcelFile = Nothing
答案 0 :(得分:1)
问题是你在字符串文字中包含双引号(")。字符串中的第一个双引号用于表示字符串的结尾。接下来是一个单引号,表示评论的开始。如果在字符串文字中包含双引号,则需要其中两个。这是更正后的陈述(为了便于阅读,我将其拆分为三行。)
oExcelsheet.Range("f2").Formula = "=IF(LEN(A2)=2,(CONCATENATE(""'00000"",A2))," _
& "IF(LEN(A2)=3,CONCATENATE(""'0000"",A2),IF(LEN(A2)=4,CONCATENATE(""'000"",A2)," _
& "IF(LEN(A2)=5,CONCATENATE(""'00"",A2),IF(LEN(A2)=6,CONCATENATE(""'0"",A2),A2)))))"