首页 > 解决方案 > 运行循环宏时 Excel 崩溃

问题描述

Stack Overflow 上有类似的问题,但是没有一个答案适用于我的问题,所以我正在写一个新问题。我正在尝试制作一个宏,它循环遍历列中的单元格,直到找到一个空单元格。然后它将一些数据(例如日期)复制到该行的单元格中。Excel 没有给我任何错误,但是当我单击按钮运行宏时,程序崩溃了。

Sub Button1()
    Dim cell As String
    cell = "A"
    Dim cellCount As Integer
    cellCount = 8

    Dim currentDate As Date

    Dim currentCell As String
    currentCell = cell & cellCount

    Do
        If IsEmpty(currentCell) = True Then
            Worksheets("Trades").Range(currentCell).Value = currentDate
            cellCount = cellCount + 1
            currentCell = cell & cellCount
        End If
    Loop Until IsEmpty(currentCell) = True
End Sub

标签: excelvba

解决方案


如果您只想检查当前单元格是否为空(不包含任何内容),我建议您使用以下内容:

currentCell = vbNullString

“vbNullString”表示来自该特定单元格的值没有返回任何字符串值。

您的另一种方法是首先找到最后一行(我想您正试图在 A 列中找到最后一行)并将该值保存到变量中。之后,您使用该值来保存日期。

Sub Button1()
Dim lastRow As Long
Dim currentDate As String

'Save current date to a string variable
currentDate = Date

'Find last row in column A and store value to variable
lastRow = Worksheets("Trades").Cells(Rows.Count, 1).End(xlUp).Row

'Save date to last row on specified column
Worksheets("Trades").Cells(lastRow, 1).Value = Date
End Sub

推荐阅读