【发布时间】:2017-05-11 00:21:13
【问题描述】:
我正在制作一个 vb.net 程序,我在 Excel 文件上写入一些数据。到目前为止,这不是问题! 但是,我在文件上写入 TimeSpan 时遇到问题。
例如上代码:
Sub DataExport()
'Create a bridge between Console and Excel:
Dim ExcelBridge As Excel.Application
ExcelBridge = New Excel.Application
Dim NewWorkbook As Excel.Workbook = ExcelBridge.Workbooks.Open("P:\HelpDesk\Definitions\Models\RPMAN.xlsm")
NewWorkbook.Application.DisplayAlerts = False
'Create Desktop folders if they don't exist:
If Dir(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Reports", vbDirectory) = "" Then
MkDir(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Reports")
End If
If Dir(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Reports\HelpDesk", vbDirectory) = "" Then
MkDir(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Reports\HelpDesk")
End If
'Test variables:
Dim test01 As Integer = 2
Dim test02 As String = "FieldA"
Dim test03 As String = "FieldB"
Dim test04 As String = "FieldC"
Dim test05 As Date = DateSerial(2017, 1, 1)
Dim test06 As Date = Now()
Dim test07 As TimeSpan = TimeSpan.Parse("1.12:03:55")
Dim test08 As String = "FieldD"
Dim test09 As TimeSpan = TimeSpan.Parse("3.20:43:07")
Dim test10 As String = "FieldE"
'Write Excel file:
With NewWorkbook.Sheets("RESUMO")
.cells(3, 1).formular1c1 = test01
.cells(3, 2).formular1c1 = test02
.cells(3, 3).formular1c1 = test03
.cells(3, 4).formular1c1 = test04
.cells(3, 5).formular1c1 = test05
.cells(3, 6).formular1c1 = test06
.cells(3, 7).formular1c1 = test07
.cells(3, 8).formular1c1 = test08
.cells(3, 9).formular1c1 = test09
.cells(3, 10).formular1c1 = test10
End With
'Save Excel file:
NewWorkbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Relatórios\HelpDesk\ITreport" & Format(Now(), "yyyyMMddHHmmss") & ".xlsm")
'Close Excel file
NewWorkbook.Close()
End Sub
我在线路上遇到错误
.cells(3, 7).formular1c1 = test07
它根本不允许我写它。
使用On Error Resume Next,代码会写入除 TimeSpan 之外的所有内容。
可能这个问题有一个简单的解决方案,但我真的没有看到它。 任何帮助将不胜感激。和往常一样,提前谢谢大家。
【问题讨论】:
-
.cells(3, 7) = test07怎么样? -
不!那也不行……
-
Dim test07 As TimeSpan = DateTime.Parse("1.12:03:55")? -
对不起!您最后的建议的任何组合都有效...
-
显然问题出在时间跨度上。尝试将其设为 ToString 并简单地将值放在那里。类似
.cells(3, 7).formular1c1 = test07.ToString(@"dd\.hh\:mm\:ss")