无法弄清楚如何使我的范围大小变量

时间:2015-04-03 19:54:19

标签: excel-vba vba excel

Sub CountHighSales()
    'This program asks the user for a threshold sales value. Then it finds the number of
    'sales in each region at least as large as the threshold. It also finds the total number
    'of sales at least as large as the threshold.
    Dim i, j As Integer         'i and j are counter variables
    Dim nHigh(6) As Integer     'nHigh is the number of sales over the threshold in each region
    Dim nHighTotal As Integer   'nHighTotal is the total number above the threshold
    Dim cutoff As Currency      'cutoff is the threshold value provided by the user
    Dim message As String       'message is text that we will report to the user
    Dim lastcolumn As Long





    'Ask the user for the threshold value and store it in the variable cutoff.
    cutoff = InputBox("What sales value do you want to check for?")
    'Count the number of sales values at least as large as cutoff.
    nHighTotal = 0              'Initialize the value of nHighTotal
    For j = 1 To 6              'Our range is 6 columns wide
        nHigh(j) = 0            'Initialize the value of nHigh(j)
        For i = 1 To 36         'Our range is 36 rows high
            If Range("SalesRange").Cells(i, j).Value >= cutoff _
                Then nHigh(j) = nHigh(j) + 1          'Increment nHigh if Sales >= cutoff
        Next i                  'Go to the next row
        'After all rows done, report the value of nHigh(j)
        'Note: the & operator joins/concatenates two strings.
        'Note: the Format function formats a numerical value using a specific formatting pattern we specify.
        message = "For region " & j & ", sales were above " & Format(cutoff, "$0,000") _
            & " on " & nHigh(j) & " of the 36 months."
        MsgBox (message)
        'Add the current regions total to nHighTotal
        nHighTotal = nHighTotal + nHigh(j)
    Next j                      'Go to the next column
    'Now report out the total number of sales exceeding the cutoff
    message = "The total number of sales, across all regions, above " & Format(cutoff, "$0,000") & " is " _
        & nHighTotal & "."
    MsgBox (message)
End Sub

抱歉,我是VBA的新手。这是我正在上课的。我无法弄清楚如何让VBA检测我拥有的行数和列数。我希望它能够检测行和列,然后能够输出该数据

1 个答案:

答案 0 :(得分:0)

有几种方法可以确定工作表上使用的最后一行和最后一列。这就是我通常在需要每个数量时使用的内容,就像在宏中一样。

Dim lastCol as integer
lastCol = Range("A1").End(xlToRight).Column

Dim lastRow as integer
lastRow = Range("A1").End(xlDown).Row

然后你可以重建你的nhigh数组

redim nhigh(1 to lastCol)

循环遍历列,然后是单元格:

for j = 1 to lastcol
    nhigh(j) = 0
    for i = 1 to lastRow
       if ....