2013-05-31 4 views
-1

Я ищу, чтобы хранить значения для графика. У нас есть два соответствующих столбца данных: A имеет имя, B имеет сумму. Что мне нужно сделать, это суммировать суммы, которые имеют одинаковое имя, вытащить первую десятку этих сумм и отобразить их на диаграмме. Возможно ли это, или мне нужно хранить первую десятку в какой-то таблице?Excel VBA- Сохранение значений для отображения позже

Спасибо!

+0

Это легко сделать с помощью сводной таблицы/поворота диаграммы топ-10 вариант, если у вас есть Excel 2013 вы можете создать диаграмму, не требуя диапазона данных. –

ответ

0

Вам нужно будет поместить все значения в одну таблицу для источника диаграммы.

Если вы не хотите, чтобы этот второй набор данных был видимым или изменен основными пользователями, вы можете добавить еще один лист, на котором вы копируете только 10 строк и установите источник диаграммы на этот лист. В новом листе вы можете пометить его в своих свойствах в редакторе VBA как «Visible = xlSheetVeryHidden», который в основном делает его видимым только формой VBA.

Возможно ли, из сценария да, вы могли бы рассчитать их сами в сценарии VBA и записать их в таблицу назначения.

Вот несколько примеров кода на перекручивание через лист в Excel (от тренировки я держал)

Sub LoopingThroughSheetContents() 

    ' This is a comment in Visual Basic, any text after a single-quote character is ignored. 
    ' Explain PURPOSE and OBJECTIVE with comments DO NOT explain the obvious it's not useful later on. 

    ' DIM statements define variables that are typically used inside a sub-routine or function (both called a method) 
    ' Variables can be passed to different methods to break up code into re-usable chunks and to simplify or generalize operation. 

    Dim Sh As Worksheet ' used to hold reference to the sheet that is being worked on. 
    Set Sh = Application.ActiveSheet 'complex objects are assigned with the "Set" statement. 
     ' basic data types such as Long, Date, String, Integer, Boolean are simply assigned and read with "=" 
     ' complex ones can have a default property that returns a value instead of the object itself. 
     ' SET indicates to assign the object and not the default property value. 

    Dim iR As Long ' Variable used to hold the CURRENT row during the loop 
    Dim iC As Long ' Variable used to hold the CURRENT Column during the loop 

    Dim Buffer As String ' used to buffer the cell values for test display. 

    ' Excel provides Range objects to work with depending on the scenario. 
    ' A Range is equivalent to a users selection in the Excel GUI (Graphical User Interface) 
    ' a built in Range Property of all WorkSheets is the "UsedRange" 
    ' UsedRange refers to the smallest rectangluar selection that incudes all data on a sheet normally starting from 1,1 (A1) 

    Dim TempCellValue As String 

    For iR = 2 To Sh.UsedRange.Rows.Count ' causes the code inside the "For Next" to run once 
     ' for each number from 1 to the last row on the sheet based on excels sheet data range that is considered USED. 
     ' each loop iR will increment by 1. Eg. 1, 2, 3, 4 ... exit 
     ' iR in the first loop is 1 

     For iC = 1 To Sh.UsedRange.Columns.Count ' another loop inside the ROW loop. 
      ' used to access each column in this case. 
      ' The column loop will start, Loop multiple times, and End once for each row because it is INSIDE the ROW loop! 
      ' If there are 3 rows and 5 columns the block of code will execute 15 times. 

      ' get the value property of the range of cells requested basically Row iR and Column iC 
      ' assigning it to the temporary variable TempCellValue 
      TempCellValue = Sh.Cells(iR, iC) 

      Buffer = Buffer & TempCellValue & vbTab ' append the value to a buffer with a trailing TAB character. 

     Next iC 'the end of the column loop. 

     Buffer = Buffer & vbCrLf ' after each column is processed add an ENTER character to the buffer to End the Rows line output 

     ' the end marker for the loop for each ROW ... 
    Next iR ' the end of the loop, code will return to the corresponding "FOR" line. 
     'with iR incremented to the next number until it is past the desired end point. 

    MsgBox Buffer 

End Sub 
+0

Итак, даже если у меня есть необработанные данные, нам все равно нужно иметь таблицу с вычисленными значениями где-нибудь, даже если она скрыта? –

+0

Да, диаграмма ожидает определенный диапазон источников. Этот диапазон может быть получен посредством вычислений, кода VBA или таких вещей, как сводные таблицы. Мне больше всего нравится сам код VBA. – DarrenMB

Смежные вопросы