Excel中的VBA编程

Excel中可以使用VBA进行编程,下面是总结的几点,几个代码示例是从Microsoft Excel Visual Basic参考中Copy过来的,以供参考。

1.Excel中“视图”,工具栏,控件工具箱。可以从控件工具中拖入各种VBA控件。

2.打开“工具“,宏,Visual Basic编辑器,可以对控件进行编程。(表格中的按钮双击后即可进入VBA代码编辑界面).

3.表格的Range属性和Cells属性使用示例:

本示例将 Sheet1 上 A1 单元格的值设置为 3.14159。

Worksheets("Sheet1").Range("A1").Value = 3.14159

本示例在 Sheet1 的 A1 单元格中创建一个公式。

Worksheets("Sheet1").Range("A1").Formula = "=10*RAND()"

本示例在 Sheet1 的单元格区域 A1:D10 上进行循环。如果某个单元格的值小于 0.001,则此代码将用 0(零)来取代该值。

  1.  
    For Each c in Worksheets("Sheet1").Range("A1:D10")
  2.  
    If c.Value < .001 Then
  3.  
    c.Value = 0
  4.  
    End If
  5.  
    Next c

本示例在名为“TestRange”的区域上进行循环,并显示该区域中空白单元格的个数。

  1.  
    numBlanks = 0
  2.  
    For Each c In Range("TestRange")
  3.  
    If c.Value = "" Then
  4.  
    numBlanks = numBlanks + 1
  5.  
    End If
  6.  
    Next c
  7.  
    MsgBox "There are " & numBlanks & " empty cells in this range"

本示例将 Sheet1 中单元格区域 A1:C5 上的字体样式设置为斜体。本示例使用 Range 属性的语法2。Worksheets("Sheet1").Range(Cells(1, 1), Cells(5, 3)).Font.Italic = True

  1.  
     
  2.  
     
  3.  
     
  4.  
    本示例将 Sheet1 中单元格 C5 的字体大小设置为 14 磅。
  5.  
    Worksheets("Sheet1").Cells(5, 3).Font.Size = 14
  6.  
     
  7.  
    本示例清除 Sheet1 上第一个单元格的公式。
  8.  
    Worksheets("Sheet1").Cells(1).ClearContents
  9.  
     
  10.  
    本示例将 Sheet1 上所有单元格的字体设置为 8 磅的“Arial”字体。
  11.  
    With Worksheets("Sheet1").Cells.Font
  12.  
        .Name = "Arial"
  13.  
        .Size = 8
  14.  
    End With
  15.  
     
  16.  
    本示例在 Sheet1 上的单元格区域 A1:J4 中循环,将其中小于 0.001 的值替换为 0(零)。
  17.  
    For rwIndex = 1 to 4
  18.  
        For colIndex = 1 to 10
  19.  
            With Worksheets("Sheet1").Cells(rwIndex, colIndex)
  20.  
                If .Value < .001 Then .Value = 0
  21.  
            End With
  22.  
        Next colIndex
  23.  
    Next rwIndex
  24.  
posted @ 2023-04-15 22:55  快乐58  阅读(154)  评论(0)    收藏  举报