通过VBA中的单击按钮进行比较和分配值

时间:2014-01-06 05:56:52

标签: excel-vba vba excel

我想通过点击按钮在列中分配一个值,如序列号。我已经制作了一个代码,但它没有按钮。我也想添加按钮。

Option Base 1
Function Check()
    Dim i As Integer
    Dim startCell As Range
    Dim firstNonEmptyCell As Range

    Set startCell = Range("G2")

    If VBA.IsEmpty(startCell.Value) Then
        MsgBox "No data in this column"
    Else
        Range("A2") = 1
        Range("A2").Select
        Selection.DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, _
        Step:=1, Stop:=400, Trend:=False
    End If
End Function

1 个答案:

答案 0 :(得分:1)

  1. 通过Form工具栏中的Insert插入Developer按钮。

    enter image description here

  2. 将以下代码粘贴到模块中,然后右键单击按钮并单击assign Macro

  3. Button1_Click对话框中选择Assign Macro,您就完成了。

  4. <强>代码

    Option Explicit
    
    Sub Button1_Click()
        Dim ws As Worksheet
        Dim LRow As Long, i As Long
    
        '~~> Change this to the relevant worsheet
        Set ws = ThisWorkbook.Sheets("Sheet1")
    
        With ws
            '~~> Find Last Row in Col G which has data
            LRow = .Range("G" & .Rows.Count).End(xlUp).Row
    
            If LRow = 1 Then
                MsgBox "No data in column G"
            Else
                For i = 2 To LRow
                    .Range("A" & i).Value = i - 1
                Next i
            End If
        End With
    End Sub