我已经为提取按钮编写了这段代码。它完美地运作。我想要做的是打开Excel应用程序并在工作表中显示数据。现在,在每次提取后,我必须转到c:
驱动器才能看到电子表格。此外,有没有办法自动更新列,更改标题颜色。谢谢!
Dim FileNum As Integer
Dim strSQL As String
Dim rs As ADODB.Recordset
Dim strFileName As String
FileNum = FreeFile
strFileName = "C:\Test\TESTFILE.CSV"
Open strFileName For Output As #FileNum
Write #FileNum, "ID", "FirstName", "LastName", "DOB", "SSN", "SEX"
Set rs = New ADODB.Recordset
strSQL = "Select ID, FirstName, LastName, DOB, SSN, Sex from dbo.tblTest_Clients Where ID = " & g_lngSelectedID
rs.Open strSQL, g_cnDatabase
rs.MoveFirst
Do While Not rs.EOF
Write #FileNum, rs("ID") & vbTab; rs("FirstName") & vbTab; rs("LastName") & vbTab; rs("DOB") & vbTab; rs("SSN") & vbTab; rs("Sex")
rs.MoveNext
Loop
rs.Close
Close #FileNum
答案 0 :(得分:0)
您正在导出CSV文件。 CSV无法存储颜色信息,因此您必须打开它,修改颜色,然后将其另存为.xlsx或类似的东西。
步骤1)使用excel打开文件,并通过宏修改标题列。您可以这样调用此宏:
Call Open_Excel("C:\Test\TESTFILE.CSV")
Trying to open the workbook in separate instance
Sub Open_Excel(ByVal path As String)
'Create a Microsoft Excel instance via code
'using late binding. (No references required)
Dim xlApp As Excel.Application
Dim wbExcel As Workbook
Dim xlSheet As Worksheet
'Create a new instance of Excel
Set xlApp = CreateObject("Excel.Application")
'Open workbook
Set wbExcel = xlApp.Workbooks.Open(path)
'Open worksheet
Set xlSheet = wbExcel.Worksheets(1)
'Set header to whatever RGB color you want, also add other header formatting here
xlSheet.UsedRange.Rows(1).Interior.Color = RGB(255,255,0)
'Autofit columns
xlSheet.UsedRange.Columns.AutoFit
'Set the instance of Excel visible. (It's been hiding until now)
xlApp.Visible = True
'Release the workbook and application objects to free up memory
Set wbExcel = Nothing
Set xlApp = Nothing
Set xlSheet = Nothing
End Sub
步骤2)您可以使用VBA执行保存,也可以保持原样,并提示您在退出时保存(正如excel通常那样)。