使用字符串值创建Excel

时间:2017-06-08 07:04:01

标签: excel vb.net vba excel-vba

我想在其中创建一个带有字符串行的Excel。现在默认情况下,excel会创建数字行,我想要设置的值是00000111.我使用的代码如下:

Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object

oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add

oSheet = oBook.Worksheets("Sheet1")

oSheet.Range("A1").Value = "0000111"
oSheet.Range("B1").Value ="Name"
oSheet.Range("C1").Value = "Name2"
oSheet.Range("D1").Value = "Phone"

oBook.SaveAs("C:\New folder\excel\" & datenw & ".xlsx")
oExcel.Quit()

亲切的问候, Ifigenia酒店

2 个答案:

答案 0 :(得分:3)

另一种方式

更改

oSheet.Range("A1").Value = "0000111"

oSheet.Range("A1").Value = "'0000111" '<~~ Notice the ' before the number

答案 1 :(得分:0)

您必须将单元格的数字格式设置为Text。所以需要在代码中添加一行。

Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object

oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add

oSheet = oBook.Worksheets("Sheet1")

oSheet.Range("A1").NumberFormat = "@"    'This is the added line
oSheet.Range("A1").Value = "0000111"
oSheet.Range("B1").Value ="Name"
oSheet.Range("C1").Value = "Name2"
oSheet.Range("D1").Value = "Phone"

oBook.SaveAs("C:\New folder\excel\" & datenw & ".xlsx")
oExcel.Quit()