如何使excel列宽根据内容自适应?
如题.生成excel时,如果每列都指定宽度太麻烦了.有没有简便些的命令能使列宽自适应啊?
[解决办法]
Option Explicit
Dim xlExcel As New Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Private Sub Command1_Click()
Dim Data(3, 1) As String
Data(0, 0) = "姓名": Data(0, 1) = "身份证号"
Data(1, 0) = "张三": Data(1, 1) = "510121198301120015"
Data(2, 0) = "李四": Data(2, 1) = "510121198301120016"
Data(3, 0) = "王五": Data(3, 1) = "510121198401120017"
On Error GoTo Errhandler
'CommonDialog1.Filter = "Excel(*.txt)
[解决办法]
*.txt"
'CommonDialog1.FilterIndex = 1
'CommonDialog1.ShowOpen
xlExcel.Application.Visible = True
xlExcel.Workbooks.Add
xlExcel.Workbooks(1).Activate
Set xlSheet = xlExcel.Workbooks(1).Worksheets(1)
xlSheet.Activate
xlSheet.Columns("B:B").NumberFormatLocal = "@" '设置B列为文本格式。经过测试,用数组填充这行可以不要。
'或者xlSheet.Range("B:B").NumberFormatLocal = "@"
xlSheet.Range("A1:B4 ") = Data()
xlSheet.Columns.EntireColumn.AutoFit 'Excel根据单元格内容自适应列宽。
Errhandler:
Exit Sub
End Sub
Private Sub Form_Unload(Cancel As Integer)
On Error Resume Next
xlBook.Close
xlExcel.Quit
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlExcel = Nothing
End Sub