Excel培训VBA操作数据库实例.pptVIP

  • 1
  • 0
  • 约5.43千字
  • 约 14页
  • 2017-06-03 发布于北京
  • 举报
Company Logo Excel精英培训网出品 VBA入门范例精解 范例简介 在本次学习之前,各人要对VBA编程基础有一定程度的了解、学习。 在后面的实例中,我们将可以学习VBA程序对SQL Server数据库的简单操作,对Excel中的表格进行边框、背景颜色、文字大小、文字类型、文字格式等等一系列的设置更改。 引用类 引用一个连接数据库的类 主过程 Sub Main() unify Sheets(X-SELL), _ SELECT * FROM [AO_CN].[hcc_risk].[V_CASH_CX] ORDER BY PROD_CODE, _ D,E,F,H,K,M,N,O,P,Q,R,S,T,U,V,W,X, _ L ThisWorkbook.Save End Sub 注意:通常在我们编写程序时,主程序应越简单越好,这样不仅自己容易维护、应用,而且能使其它用户易读懂。 注释:在过程main()中,调用子过程unify,并向unify中传递四个参数;再调用VBA内部过程Thisworkbook.Save保存电子表格(执行完成如下:)。 Private Sub unify(ByVal sht As Worksheet, _ ByVal strSql As String, _ ByVal strPercentColumns As String, _ ByVal strDecimalColumns As String) clearSht sht FillData sht, strSql lineJin sht colorSheet sht percentJin sht, strPercentColumns, 0.00% percentJin sht, strDecimalColumns, 0.00 FontSheet sht, Calibri, 10 Columns(A:Z).AutoFit End Sub 整合子过程片段 注释:定义私有过程unify,并定义四个参数sht、strSql、strPercentColums、strDecimalColumns。 调用子过程clearSht、FillData、lineJin、colorSheet、percentJin、percentJin、FontSheet、Columns。由于需要向子过程片段中传递一些相同的参数,并且每次都要执行些子过程,那么我们在编程时可以整合它们在一起,减少编译次数,节省执行时间。 Private Function getRowCount(ByVal sht As Worksheet) As Long Dim lRowsNum As Long Dim i As Long For i = 3 To 65535 If sht.Cells(i, 1).Value = Then lRowsNum = i - 1 Exit For End If Next getRowCount = lRowsNum End Function 记录表格中的数据行数 注释:这里i定义为表格的行号,列号1(A)不变,从第三行开始循环一直到65535行,如果Ai中的值为空就会跳出循环,那么行数: getRowCount=i-1 Ai=“”? i 否 i+1 RowCount=i-1 是 记录表格中的数据列数 Private Function getColumnCount(ByVal sht As Worksheet) As Long Dim lColumnsNum As Long Dim i As Integer For i = 1 To 255 If sht.Cells(2, i).Value = Then lColumnsNum = i - 1 Exit For End If Next getColumnCount = lColumnsNum End Function 注释:这里i定义为表格的列号,行号2不变,从第一列开始循环一直到255列,如果i2中的值为空就会跳出循环,那么列数: getColumnCount=i-1 清除表格中记录 Private Sub clearSht(ByVal sht As Worksheet

文档评论(0)

1亿VIP精品文档

相关文档