码迷,mamicode.com
首页 > 编程语言 > 详细

VBA操作Excel

时间:2015-06-29 19:45:10      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

几个小知识:

  1、设置单元格格式:

      sht.Cells(4, pCol).NumberFormatLocal = "yyyy-mm-dd hh:mm:ss"

      其中文本格式为:"@",常规格式为:G/通用格式

  2、设置单元格为自动列宽或自动高度:

       #1、VBA自动生成的代码为:Columns("A:D").EntireColumn.AutoFit

      #2、但是字母的A到D,我们在VBA中不方便取到,一般都是数据,所以使用

          Range(Cells(1, 1), Cells(1, 40)).EntireColumn.AutoFit-----(这种方式是按照某一行的格式去适应的)

        或者、Range(Columns(1), Columns(40)).EntireColumn.AutoFit

  3、关于DoEvents事件:

     这个用的不好,只做记录,

      如下代码:

Public Sub getTableKey()
    Dim strKey As String
    Dim sql As String
    Dim strTableName As String
    Dim strPK As String
     提示框标识
    Dim bln As Boolean: bln = False
    SQL
    sql = "select a.column_name from user_cons_columns a, user_constraints b  where a.constraint_name = b.constraint_name and b.constraint_type = ‘P‘ and a.table_name = ‘"
     表名
    strTableName = getTableName()
    设置表名为大写
    strTableName = UCase(strTableName)
    写回Excel
    ActiveSheet.Cells(8, 1).Value = strTableName
    strKey = getUserPK()
    If strKey = "" Then
        连接串
        Dim ConnDB As ADODB.Connection
        Set ConnDB = New ADODB.Connection
        
        Dim ConnStr As String
         结果集
        Dim DBRst As ADODB.Recordset
        Set DBRst = New ADODB.Recordset
        ConnStr = getConnStr()
        ConnDB.Open ConnStr
        
        DoEvents
        processFM.Show 0
        DoEvents
        DBRst.Open sql & strTableName & "", ConnStr
        If DBRst.EOF And DBRst.BOF Then
            Unload processFM
            MsgBox "表名错误!", vbCritical, "错误"
            Exit Sub
        End If
        strPK = DBRst.Fields.Item(0).Value
        写回Excel
        ActiveSheet.Cells(6, 1).Value = strPK
        bln = True
        关闭
        DBRst.Close
        ConnDB.Close
    End If
    If bln Then
        Unload processFM
        MsgBox "表名更新成功!", vbInformation, "提示"
    End If
End Sub

其中的DoEvents能保证出现的窗口正常显示。

这个有待研究,但是VBA中除去大量数据外,用的不多。

  4、VBA读取Excel单元格内容:

      #1、读取实际值,使用Cells.value

      #2、读取Excel显示的值,使用Cells.Text-------------------但是这里需要注意的是Excel中有可能显示为#######,这时候需要调整列宽,方法在上文已经有阐述了。

VBA操作Excel

标签:

原文地址:http://www.cnblogs.com/IDECIDETODOIT/p/4607867.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!