我已经从Access vba创建了一个excel xls文件。
Private Sub ModifyXl()
Dim XLapp As Excel.Application
Dim xlWB As Excel.Workbook
Set XLapp = New Excel.Application
Dim xlSh As Excel.Worksheet
Set xlWB = XLapp.Workbooks.Open(DskTp & "NHL Doctors.xls", , False)
Set xlSh = xlWB.Sheets("NHLDocs")
Cells.Select
Selection.Font.Name = "Trebuchet MS"
Rows("1:1").Select
Selection.Font.Bold = True
Range("A1").HorizontalAlignment = xlCenter
Columns("A:A").EntireColumn.AutoFit
xlWB.Save
xlWB.Close
XLapp.Quit
Set XLapp = Nothing
End Sub
'Cells.Select'不起作用,但文件现在存在。我不能删除它,因为它说它已经打开 - 但它看起来不是开放的。
我已经在互联网上搜索,试图找到关闭文件并退出excel的代码 - 但没有成功。救命啊!
答案 0 :(得分:3)
您的代码无效,因为您尚未激活工作表(添加xlSh.Activate
)。但这不是解决问题的最佳方式。尝试avoid using Select/Active statements,如下面的代码:
Private Sub ModifyXl()
Dim XLapp As Excel.Application
Dim xlWB As Excel.Workbook
Set XLapp = New Excel.Application
Dim xlSh As Excel.Worksheet
'Dim DskTp as String
'DskTp = "C:\"
Set xlWB = XLapp.Workbooks.Open(DskTp & "NHL Doctors.xls", , False)
Set xlSh = xlWB.Sheets("NHLDocs")
With xlSh
.Cells.Font.Name = "Trebuchet MS"
.Range("1:1").Font.Bold = True
.Range("A1").HorizontalAlignment = xlCenter
.Range("A:A").EntireColumn.AutoFit
End With
xlWB.Close True
Set xlWB = Nothing
XLapp.Quit
Set XLapp = Nothing
End Sub
BTW,找不到初始化DskTp
变量的位置(它是一个全局变量吗?)。我已经将它的初始化添加为注释(如果你没有使用全局变量 - 取消注释thouse行)。