将Excel单元格alignment中心VB – xlCenter未声明

我使用Visual Studio 2013 Visual Basic,MS ACCESS 2013,EXCEL 2013

我的程序另存为我的datagrid中的数据为Excel。 我使用访问2013作为我的数据库这是我的代码:

Imports System.Data.OleDb Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'TODO: This line of code loads data into the 'AccessdbtestDataSet.country' table. You can move, or remove it, as needed. Me.CountryTableAdapter.Fill(Me.AccessdbtestDataSet.country) End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim con As New OleDbConnection Dim query As String = "SELECT * FROM country" con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=accessdbtest.accdb" con.Open() Dim dt As New DataTable Dim ds As New DataSet ds.Tables.Add(dt) Dim da As New OleDbDataAdapter(query, con) da.Fill(dt) DataGridView1.DataSource = ds.Tables(0) con.Close() End Sub Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value Dim i As Integer Dim j As Integer xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") xlWorkSheet.Range("A1:D1").MergeCells = True xlWorkSheet.Cells(1, 1) = "Republic of the Philippines" //I got a problem in this line of code. The program gives a message that xlCenter is not declared xlWorkSheet.Range("H15:H16").VerticalAlignment = xlCenter For i = 1 To DataGridView1.RowCount - 2 For j = 0 To DataGridView1.ColumnCount - 1 xlWorkSheet.Cells(i + 1, j + 1) = _ DataGridView1(j, i).Value.ToString() Next Next xlWorkSheet.SaveAs("C:\excel\vbexcel.xlsx") xlWorkBook.Close() xlApp.Quit() releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) MsgBox("You can find the file C:\vbexcel.xlsx") End Sub 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 

我的问题是程序给出的消息:

'xlCenter'没有被声明。 由于其保护级别,可能无法访问

xlCenterMicrosoft.Office.Interop.Excel.Constants的成员。

由于您将Microsoft.Office.Interop.Excel分配给名称Excel ,因此可以像这样引用该常量…

 xlWorkSheet.Range("H15:H16").VerticalAlignment = Excel.Constants.xlCenter 

您将需要自己声明它不包含在该导入(它是System.Windows的一部分)

 Const xlCenter = -4108