使用VBA Excel我试图计算条目

时间:2017-08-28 13:16:53

标签: excel-vba vba excel

我想确定非空白单元格中列中的空白单元格数。我有一张excel电子表格,显示去年一只股票的每日收盘价。 excel中的每一行按时间顺序列出每日收盘价。电子表格列出了我购买股票的那天以及我在相关行上卖出股票的那天。特定列用于记录日期。电子表格的摘录包含在下面。

  Stock       Date       ClosingPrice    Entered/Exited    DaysHeld?   
 -------- ------------- --------------- ----------------- ------------ 
  Apple    01/02/2017          116.25    Bought                        
  Apple    01/03/2017          119.75                                  
  Apple    01/04/2017          117.50                                  
  Apple    01/05/2017          118.75    Sold                          

我正在尝试使用VBA excel中的循环确定“已输入”行与“已退出”行标题下的“已退出”行之间的空白单元格数量,因为我交易了许多股票并且每次复制和粘贴一个excel公式时间变得耗费时间。

编译了下面的代码来计算空白单元格的数量,但它总是返回值1.在下面的代码中,单元格AI56是我购买股票的那一天,在“已输入/已退出”列标题下“买入”

Sub SandpitCountBlankCells()

' SandpitCoutBlankCells Macro
' Macro calculates the number of blank spaces
'

'Step 1: Declare variables
 Dim CountBlankCells As Long
 CountBlankCells = 0

'Select Cell AI56
Range("AI56").Select
ActiveCell.Offset(-1, -1).Range("A1").Select

'Check wheher the cell in the previous row is blank
If ActiveCell.Value = Blank Then
CountBlankCells = CountBlanksCells + 1

'While loop to check whether cells in the previous rows are blank
While ActiveCell.Value = Blank
ActiveCell.Offset(-1, 0).Range("A1").Select
ActiveCell.Select
CountBlankCells = CountBlanksCells + 1

'Place the value of the number of blank cells in cell AL56
Range("AJ56").Value = CountBlankCells

'Exit the loop
Wend

Range("AJ56").Value = CountBlankCells


End If


End Sub

2 个答案:

答案 0 :(得分:0)

当你把:

 Option Explicit 

在vba模块的顶部,您将看到存在类型错误并且尚未声明CountBlanksCells:

 CountBlankCells = CountBlanksCells + 1

应该是:

 CountBlankCells = CountBlankCells + 1

此外,compliler也不喜欢'空白'改为使用:

  While ActiveCell.Value = Empty

答案 1 :(得分:0)

最好尽可能避免使用SelectActiveCell(请参阅文档中的VBA最佳实践)。这个方法将循环遍历列AI中的所有内容,并为每个实例吐出空白,而不是仅仅显示AI56中的空白。

Sub CountDays()
Dim ws As Worksheet
Dim x As Long, y As Long
Dim entExtCol As Long, daysHeldCol As Long, startRow As Long, endRow As Long

On Error GoTo ErrHandler

Set ws = ActiveSheet
entExtCol = 35 'Col AI
daysHeldCol = 36 'Col AJ
startRow = 2 'start of data
endRow = ws.Cells(ws.Rows.Count, entExtCol).End(xlUp).Row 'end of data

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For x = startRow To endRow
    If ws.Cells(x, entExtCol) = "Bought" Then
        ct = 0
        For y = x To endRow
            If ws.Cells(y, entExtCol) = "Sold" Then
                ws.Cells(x, daysHeldCol) = ct
                Exit For
            Else
                ct = ct + 1
            End If
        Next y
    End If
Next x

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

ErrHandler:

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub