2015-04-03 58 views
0
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检测我拥有的行数和列数。我希望它能够检测行和列,然后能够输出该数据不能弄清楚如何让我的范围大小可变

+0

当你说“范围”你说的是一个单元格区域?什么是'nHighTotal'?什么是'nhigh(j)'?为什么会有'for'循环没有任何内容?没有足够的信息来了解你想要做什么。 – JNevill 2015-04-03 20:02:58

+0

只是更新了它 – 2015-04-03 20:16:18

回答

0

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

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

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

然后你可以重建你的N高阵列

redim nhigh(1 to lastCol) 

并通过列循环,然后细胞:

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