问题
Im using Visual Studio 2013 Visual Basic, MS ACCESS 2013, EXCEL 2013
My program Save As the data in my datagrid to excel. I use access 2013 as my database Here is my code:
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
My problem is The program gives the message:
'xlCenter' is not declared. It may be inaccessible due to its protection level
回答1:
xlCenter
is a member of Microsoft.Office.Interop.Excel.Constants
.
Since you assigned Microsoft.Office.Interop.Excel
to the name Excel
, you can reference that constant like this ...
xlWorkSheet.Range("H15:H16").VerticalAlignment = Excel.Constants.xlCenter
回答2:
You will need to declare it yourself as its not included in that import( its part of System.Windows)
Const xlCenter = -4108
来源:https://stackoverflow.com/questions/28915252/align-excel-cell-to-center-vb-xlcenter-is-not-declared