---
title: "VB 将数据快速导入EXCEL "
author: "yeuego"
date: "2011-03-09T13:21:20Z"
tags: ["Excel", "SQL", "VB"]
categories: ["研发管理"]
slug: "vb-excel"
draft: false
lastmod: "2011-03-09T13:21:20Z"
id: 948247
url: "https://yeuego.iteye.com/blog/948247"
---

> Public Function ToExcel()  
> On Error GoTo ErrorHandler
> 
> Dim exlapp As Excel.Application  
> Dim exlbook As Excel.Workbook  
> Set exlapp = CreateObject("Excel.Application")  
> Set exlbook = exlapp.Workbooks.Add  
> exlapp.Caption = "数据正在导出......"  
> exlapp.Visible = True  
> exlapp.DisplayAlerts = False
> 
> Dim exlsheet As Excel.Worksheet
> 
> Set exlsheet = exlbook.Worksheets.Add
> 
> exlsheet.Activate  
> Set exlsheet = exlsheet  
> exlsheet.Name = "【我导出的数据】"
> 
> '设置列宽  
> exlapp.ActiveSheet.Columns(1).ColumnWidth = 10
> 
> exlapp.ActiveSheet.Columns(2).ColumnWidth = 20
> 
> StrSql = "【你的SQL语句】"
> 
> Set exl\_rs = PubSysCn.Execute(StrSql)
> 
> exlsheet.Range("A2").CopyFromRecordset exl\_rs
> 
> exl\_rs.Close  
> Set exl\_rs = Nothing
> 
> exlapp.Worksheets("sheet1").Delete  
> exlapp.Worksheets("sheet2").Delete  
> exlapp.Worksheets("sheet3").Delete  
> exlapp.DisplayAlerts = True  
> exlapp.Caption = "数据导出完毕！！"  
> exlapp.Visible = True
> 
> Set exlapp = Nothing  
> Set exlbook = Nothing  
> Set exlsheet = Nothing
> 
> Exit Function
> 
> ErrorHandler:  
> MsgBox "EXCEL : " & err.Number & " : " & err.Description  
> End Function