Обновление ячейки в excel vba

I am using all the solutions that appear in:

How to refresh ALL cell through VBA

Getting Excel to refresh data on sheet from within VBA

ActiveSheet.EnableCalculation = False  
ActiveSheet.EnableCalculation = True

or

Application.Calculate

or

Application.CalculateFull

None of them works in Excel 2010. When I go to the cell and right click refresh it works. How can I refresh within VBA?

Sheets("Name_of_sheet").Range("D424").Refresh raises an

exception 438

Questions:

  1. How can I make the script support Excel 2003, 2007, 2010?
  2. How can I choose the source file to refresh from using VBA?

EDIT:

  1. I want to simulate a right mouse click and choose refresh in the menu in worksheet 3. That is the entire story.

  2. I work on an Excel file created 10 years ago. When opening in Excel 2010, I can go to a cell and right click on it and choose refresh and then choose the .txt file to refresh from. I am trying to do it automatically within VBA.

Community's user avatar

asked Nov 22, 2012 at 13:39

0x90's user avatar

6

You could try using Application.Calculation

Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic

answered Nov 22, 2012 at 13:42

Anirudh Ramanathan's user avatar

4

For an individual cell you can use:

Range("D13").Calculate

OR

Cells(13, "D").Calculate

0x90's user avatar

0x90

38.9k36 gold badges163 silver badges244 bronze badges

answered Nov 22, 2012 at 13:46

InContext's user avatar

InContextInContext

2,46112 silver badges24 bronze badges

1

I finally used mouse events and keystrokes to do it:

Sheets("worksheet34").Select
Range("D15").Select
Application.WindowState = xlMaximized
SetCursorPos 200, 600 'set mouse position at 200, 600
Call mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0) 'click left mouse
Application.SendKeys ("R")

answered Nov 29, 2012 at 5:52

0x90's user avatar

0x900x90

38.9k36 gold badges163 silver badges244 bronze badges

2

just a reminder;

be careful when using

Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic

this sets the entire excel application to calculate formula’s either automatically or manually. If you use

Application.Calculation = xlCalculationManual

you’ll notice your automatic formulas no longer work.

cheers

answered Feb 16, 2016 at 17:53

LeeF's user avatar

You can force excel to recalculate a cell or range of cells by marking the cell/range as dirty.

Example :

' Recalculate Column D4 to D24
Sheets("Name_of_sheet").Range("D4:D24").Dirty

or

' Recalculate Cell D4<br>
Sheets("Name_of_sheet").Range("D4").Dirty<br>

Ike's user avatar

Ike

7,8904 gold badges11 silver badges29 bronze badges

answered Sep 5, 2021 at 11:16

XYZLOL's user avatar

Application.Calculate didn’t work for my function. Not even when followed by DoEvents.

What I found that works is to re-enter the formula in the cell.
A simple way to get the formula is to start recording a macro, use F2 to edit the cell, then press enter. The macro will make a great copy of the function text with all needed quotes.

Below is an example.

Sheets("Name_of_sheet").Range("D424").FormulaR1C1 = "=now()"

svyat1s's user avatar

svyat1s

8689 gold badges12 silver badges21 bronze badges

answered Mar 5, 2021 at 19:36

Scott's user avatar

Cells(x, y).Select
ActiveCell.FormulaR1C1 = Selection.Value

works perfectly for me

answered Aug 2, 2022 at 20:21

user19260138's user avatar

I have a long «macro» in a workbook > 20 MB, tens of thousands of lines, that calls a dll written in Fortran. None of these methods worked:

Call Application.Calculate
Call Application.CalculateFull
Call Application.CalculateFullRebuild
Re-entering the formula
Range.Dirty

Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic

ThisWorkbook.ActiveSheet.EnableCalculation = False
ThisWorkbook.ActiveSheet.EnableCalculation = True

This worked:

On Error Resume Next
Application.SendKeys "{F2}{Enter}{NumLock}"  'SendKeys turns off NumLock for some reason
On Error GoTo 0

This even worked when a chart was selected.

answered Feb 9 at 14:47

Rocky Scott's user avatar

Rocky ScottRocky Scott

4364 silver badges13 bronze badges

Вопрос:

Как обновить ВСЕ ячейку через VBA

Как получить Excel для обновления данных на листе из VBA?

Я использую все решения, которые появляются выше:

ActiveSheet.EnableCalculation = False
ActiveSheet.EnableCalculation = True

или

Application.Calculate

или

Application.CalculateFull

но ни один из них не работает в excel 2010, когда я иду в ячейку и правой кнопкой мыши refresh работает. Как обновить его в VBA.

Эта опция: Sheets("Name_of_sheet").Range("D424").Refresh поднять exception 438.

вопросы:

  • Как я могу сделать script поддержку excel 2003,2007,2010?
  • Как я могу выбрать, используя VBA исходный файл для обновления?

EDIT:

  • Я хочу имитировать щелчок правой кнопкой мыши и выбор обновления в меню worksheet 3. что вся история.

  • Я работаю над файлом excel, который был создан 10 лет назад. Открыв его в excel 2010, я могу перейти в ячейку и щелкнуть правой кнопкой мыши по ней и выбрать обновление, а затем выбрать файл .txt для обновления, и он работает отлично. Теперь, когда я пытаюсь сделать это автоматически в VBA, весь код, указанный выше, не помогает.

Лучший ответ:

Вы можете попробовать использовать Application.Calculation

Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic

Ответ №1

Для отдельной ячейки вы можете использовать:

Range("D13").Calculate

ИЛИ

Cells(13, "D").Calculate

Ответ №2

просто напоминание;

будьте осторожны при использовании

Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic

это устанавливает полное приложение excel для вычисления формулы автоматически или вручную. Если вы используете

Application.Calculation = xlCalculationManual

вы заметите, что ваши автоматические формулы больше не работают.

веселит

Ответ №3

Я, наконец, использовал мышиные события и нажатия клавиш:

Sheets("worksheet34").Select
Range("D15").Select
Application.WindowState = xlMaximized
SetCursorPos 200, 600 'set mouse position at 200, 600
Call mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0) 'click left mouse
Application.SendKeys ("R")

Я использую все решения, которые есть в:

Как обновить ВСЮ ячейку через VBA

Получение Excel для обновления данных на листе из VBA

ActiveSheet.EnableCalculation = False  
ActiveSheet.EnableCalculation = True

Или

Application.Calculate

Или

Application.CalculateFull

Ни один из них не работает в Excel 2010. Когда я перехожу к ячейке и щелкаю правой кнопкой мыши «Обновить», она работает. Как я могу обновиться в VBA?

Sheets("Name_of_sheet").Range("D424").Refresh поднимает

исключение 438

Вопросов:

  1. Как сделать так, чтобы скрипт поддерживал Excel 2003, 2007, 2010?
  2. Как я могу выбрать исходный файл для обновления с помощью VBA?

РЕДАКТИРОВАТЬ:

  1. Я хочу имитировать щелчок правой кнопкой мыши и выбрать обновление в меню в worksheet 3. Вот и вся история.

  2. Я работаю над файлом Excel, созданным 10 лет назад. При открытии в Excel 2010 я могу перейти к ячейке, щелкнуть ее правой кнопкой мыши и выбрать «Обновить», а затем выбрать файл .txt для обновления. Я пытаюсь сделать это автоматически в VBA.

7 ответов

Лучший ответ

Вы можете попробовать использовать Application.Calculation

Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic


2

Anirudh Ramanathan
22 Ноя 2012 в 17:49

Наконец, я использовал для этого события мыши и нажатия клавиш:

Sheets("worksheet34").Select
Range("D15").Select
Application.WindowState = xlMaximized
SetCursorPos 200, 600 'set mouse position at 200, 600
Call mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0) 'click left mouse
Application.SendKeys ("R")


1

0x90
29 Ноя 2012 в 21:24

Просто напоминание;

Будьте осторожны при использовании

Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic

Это настраивает все приложение Excel на автоматический или ручной расчет формул. Если вы используете

Application.Calculation = xlCalculationManual

Вы заметите, что ваши автоматические формулы больше не работают.

Ура


1

LeeF
16 Фев 2016 в 20:53

Application.Calculate не работал с моей функцией. Даже когда за ним следует DoEvents.

Я обнаружил, что работает — это повторно ввести формулу в ячейку. Простой способ получить формулу — начать запись macro, использовать F2 для редактирования ячейки, а затем нажать enter. Макрос сделает отличную копию функционального текста со всеми необходимыми кавычками.

Ниже приведен пример.

Sheets("Name_of_sheet").Range("D424").FormulaR1C1 = "=now()"


0

svyat1s
9 Мар 2021 в 18:12

Для отдельной ячейки вы можете использовать:

Range("D13").Calculate

ИЛИ

Cells(13, "D").Calculate


2

0x90
22 Ноя 2012 в 17:48

Cells(x, y).Select
ActiveCell.FormulaR1C1 = Selection.Value

Отлично работает для меня


0

user19260138
2 Авг 2022 в 23:21

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

Пример :

' Recalculate Column D4 to D24
Sheets("Name_of_sheet").Range("D4:D24").Dirty

Или

' Recalculate Cell D4<br>
Sheets("Name_of_sheet").Range("D4").Dirty<br>

We use VBA to automate our tasks in excel. The idea of using VBA is to connect the interface of excel with the programming. One of the very most connections between them is by changing the cell values. The change in cell value by programming shows the power of VBA. In this article, we will see how to set, get and change the cell value. 

Set Cell Value

Assigning a cell with a value can be achieved by very two famous functions in VBA i.e. Range and Cells function. 

Range Function in VBA

The range function helps access the cells in the worksheet. To set the cell value using the range function, we use the .Value

Syntax: Range(cell_name).Value = value_to_be_assinged. 

Set the value to a single cell

If you want to assign ’11’ to cell A1, then the following are the steps: 

Step 1: Use the Range function, in the double quotes type the cell name. Use .Value object function. For example, Range(“A1”).Value = 11

Applying-range-function

Step 2: Run your macro. The number 11 appears in cell A1

Running-macro

Set the value to multiple cells at the same time

Remember the days, when your teacher gives you punishment, by making you write the homework 10 times, those were the hard days, but now the effort has exponentially reduced. You can set a value to a range of cells with just one line of code. If you want to write your name, for example, “Arushi” 10 times, in the range A2 to A11. Use range function. Following are the steps: 

Step 1: Use the Range function, in the double quotes, write “Start_of_cell: End_of_cell”. Use .Value object function. For example, Range(“A2:A11”).Value = “Arushi”

Applying-range-function

Step 2: Run your macro. The text “Arushi” appears from cell A2 to A11 inclusive. 

Running-macro

Cells Function in VBA

The Cells function is similar to the range function and is also used to set the cell value in a worksheet by VBA. The difference lies in the fact that the Cells function can only set a single cell value at a time while the Range function can set multiple values at a time. Cells function use matrix coordinate system to access cell elements. For example, A1 can be written as (1, 1), B1 can be written as (1, 2), etc. 

Syntax: Cells(row_number, column_number).Value = value_to_be_assign

For example, you want to set the cell value to “Arushi cleared CA with Rank “, in cell B1. Also, set cell C1, to ‘1’. Following are the steps:

Step 1: Open your VBA editor. Use cells function, as we want to access cell B1, the matrix coordinates will be (1, 2). Type, Cells(1, 2).Value = “Arushi cleared CA with Rank” in the VBA code. 

Using-cell-functions

Step 2: To access cell C1, the matrix coordinates are (1, 3). Type, Cells(1, 3).Value = 1 in the VBA code. 

Accessing-cell-C1

Step 3: Run your macro. The required text appears in cell B1, and a number appears in C1. 

Running-macro

Setting Cell values by Active cell and the input box

There are other ways by which you can input your value in the cell in a worksheet. 

Active Cell 

You can set the cell value of a cell that is currently active. An active cell is the selected cell in which data is entered if you start typing. Use ActiveCell.Value object function to set the value either to text or to a number. 

Syntax: ActiveCell.Value = value_to_be_assigned

For example, you want to assign the active cell with a text i.e. “Arushi is practicing CA”, also want to change the color of the cell to yellow. Following are the steps: 

Step 1: Use the ActiveCell object to access the currently selected cell in the worksheet. Use ActiveCell.Value function object to write the required text. 

Using-active-cell-function

Step 2: Color the cell by using ActiveCell.Interior.Color function. For example, use vbYellow to set your cell color to yellow. 

Using-active.cell.interior.color-function

Step 3: Run your macro. The currently selected cell i.e. B1 has attained the requirements. 

Running-macro

Input Box

You can use the input box to set the cell value in a worksheet. The input box takes the custom value and stores the result. This result could further be used to set the value of the cell. For example, set the cell value of A1, dynamically by taking input, from the input box.

Following are the steps

Step 1: Open your VBA editor. A sub-procedure name geeks() is created. Use the Range function to store the value given by the input box. 

Using-range-function

Step 2: Run your Macro. A dialogue-box name Microsoft Excel appears. Enter the value to be stored. For example, “geeks for geeks”. Click Ok

Entering-value-to-be-stored

Step 3: Open your worksheet. In cell A1, you will find the required text is written. 

Text-written-in-A1

Get Cell Value

After setting the cell value, it’s very important to have a handsome knowledge of how to display the cell value. There can be two ways two get the cell value either print the value in the console or create a message box. 

Print Cell Value in Console

The console of the VBA editor is the immediate window. The immediate window prints the desired result in the VBA editor itself. The cell value can be stored in a variable and then printed in the immediate window. For example, you are given a cell A1 with the value ’11’, and you need to print this value in the immediate window. 

Following are the steps

Step 1: Press Ctrl + G to open the immediate window. 

Opening-immediate-window

Step 2: The cell value in A1 is 1

Value-in-A1

Step 3: Open your VBA editor. Declare a variable that could store the cell value. For example, Val is the variable that stores the cell value in A1. Use the Range function to access the cell value. After storing the cell value in the val, print the variable in the immediate window with the help of Debug.Print(val) function.

Printing-variable-in-immediate-window

Step 4: Run your macro. The cell value in A1 is printed in the immediate window. 

Running-macro

Print Cell Value in a Message Box 

A message box can also be used to show the cell value in VBA. For example, a random string is given in cell A1 of your string i.e. “Arushi studies in Hansraj”. Now, if you want to display the cell value in A1, we can use Message Box to achieve this. 

Text-present-in-A1

Following are the steps

Step 1: Open your VBA macro. Create a message box by using MsgBox. Use the Range(cell).Value function to access the cell value. 

Creating-a-message-box

Step 2: Run your macro. A message box appears, which contains the cell value of A1

Running-macro

Change Cell Values 

The value, once assigned to the cell value, can be changed. Cell values are like variables whose values can be changed any number of times. Either you can simply reassign the cell value or you can use different comparators to change the cell value according to a condition. 

By reassigning the Cell Value

You can change the cell value by reassigning it. In the below example, the value of cell A1 is initially set to 1, but later it is reassigned to 2

Following are the steps

Step 1: Open your VBA code editor. Initially, the value of cell A1 is assigned to 1. This initial value is printed in the immediate window. After that, we changed the value of cell A1 to 2. Now, if we print the A1 value in the immediate window, it comes out to be 2

Changing-value-in-cell

Step 2: The immediate window shows the output as 1 and 2. 

Immediate-window-shows-output

Changing cell value with some condition

We can use if-else or switch-case statements to change the cell value with some condition. For example, if your age is greater than 18 then you can drive else you cannot drive. You can output your message according to this condition. 

Following are the steps

Step 1: A code is written in the image below, which tells whether you are eligible for a driving license or not. If your age is greater than 18 then cell A1 will be assigned with the value, “You are eligible for the driving license”, else A1 will be assigned with “You are not eligible for driving license”. 

Text-assigned-to-A1

Step 2: Run your macro. An input box appears. Enter your age. For example, 19. 

Running-macro

Step 3: According to the age added the cell value will be assigned. 

Cell-value-assigned

RRS feed

  • Remove From My Forums

 none

Вызов макроса на обновление ячейки

RRS feed

  • Вопрос

  • Вопрос в общем в сабже. Как вызывать макрос при обновлении ячейки, если её значение равно какому-то определенному? В макрос нужно передавать в качестве параметров информарцию по ячейке (строка, столбец, значение), которая вызвала макрос. Спасибо заранее.

Ответы

  •  sHDa написано:

    значит так. сейчас я так и работаю с этими событиями. если бы меня все устраивало, не спрашивал бы. вы мне что-то посоветовать хотите или просто руки чешутся? если хотите посоветовать — советуйте, если нет, то не надо сюда писать. в ваших комментариях я не нуждаюсь.

    К большому сожалению, в Excel отсутствуют события привязанные к конкретным ячейкам. Вы получаете событие при обновлении листа, затем отфильтровываете диапазон и получаете событие необходимого Вам диапазона.

    Или отслеживате событие «изменения диапазона», но это, ИМХО, способ менее удачный.

    Других вариантов не получится.

    ======================================================

    А по поводу советов. Если бы Вы в вопросе сразу прописали какие варианты Вами уже опробованы, так и не получили бы бесполезных ответов.

    Попробуйте поискать в

    QUE 2007 «VBA for the 2007 Microsoft Office System»

    события Excel неплохо описаны в

    OReilly 2002 «Writing Excel Macros with VBA»

    можно посмотреть Wiley 2007 «Excel 2007 Bible»

    цитата:

    «

    Understanding Events

    Excel is capable of monitoring a wide variety of events and executing your VBA

    code when a particular event occurs. This chapter covers the following types of

    events.


    n Workbook events: These occur for a particular workbook. Examples


    include Open (the workbook is opened or created), BeforeSave (the


    workbook is about to be saved), and NewSheet (a new sheet is

    added). VBA code for workbook events must be stored in the

    ThisWorkbook code module.


    n Worksheet events: These occur for a particular worksheet. Examples


    include Change (a cell on the sheet is changed), SelectionChange


    (the cell pointer is moved), and Calculate (the worksheet is recalculated).

    VBA code for worksheet events must be stored in the code module

    for the worksheet (for example, the module named Sheet1).


    n Events not associated with objects: The final category consists of two


    useful application-level events: OnTime and OnKey. These work differently

    from other events.

    «


Все ответы

  • Неужто не знает никто? Wink

  • Code Snippet

    Private Sub Worksheet_Change(ByVal Target As Range)

    If ((Target.Row = 3) And (cR = Target.Column)) Then

            MsgBox «C3: Changed»
        MsgBox Target.Value
    End If

    End Sub

  • Спасибо за ответ, но хотелось бы чтобы вызов происходил при обновлении конкретных ячеек, а не любой ячейки с листа.

  • А в чём проблема поэксперементировать?:

    Code Snippet

    Private Sub Worksheet_Change(ByVal Target As Range)

    If ((Target.Row = 3) And (Target.Column = 3)) Then
        MsgBox Target.Value

        ‘или любые другие действия
    End If

  • с чем экспериментировать? это сообщение приходит на любое обновление листа

  •  sHDa написано:

    с чем экспериментировать? это сообщение приходит на любое обновление листа

    значит не судьба. у меня работает.

    поэксперементировать с событиями, в каких-то случаях может помочь Calculate, в каких-то Change.

    Вообще вы в курсе о существовании поисковых систем типа yandex, google?

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


  • значит так. сейчас я так и работаю с этими событиями. если бы меня все устраивало, не спрашивал бы. вы мне что-то посоветовать хотите или просто руки чешутся? если хотите посоветовать — советуйте, если нет, то не надо сюда писать. в ваших комментариях я не нуждаюсь.

  •  sHDa написано:

    значит так. сейчас я так и работаю с этими событиями. если бы меня все устраивало, не спрашивал бы. вы мне что-то посоветовать хотите или просто руки чешутся? если хотите посоветовать — советуйте, если нет, то не надо сюда писать. в ваших комментариях я не нуждаюсь.

    К большому сожалению, в Excel отсутствуют события привязанные к конкретным ячейкам. Вы получаете событие при обновлении листа, затем отфильтровываете диапазон и получаете событие необходимого Вам диапазона.

    Или отслеживате событие «изменения диапазона», но это, ИМХО, способ менее удачный.

    Других вариантов не получится.

    ======================================================

    А по поводу советов. Если бы Вы в вопросе сразу прописали какие варианты Вами уже опробованы, так и не получили бы бесполезных ответов.

    Попробуйте поискать в

    QUE 2007 «VBA for the 2007 Microsoft Office System»

    события Excel неплохо описаны в

    OReilly 2002 «Writing Excel Macros with VBA»

    можно посмотреть Wiley 2007 «Excel 2007 Bible»

    цитата:

    «

    Understanding Events

    Excel is capable of monitoring a wide variety of events and executing your VBA

    code when a particular event occurs. This chapter covers the following types of

    events.


    n Workbook events: These occur for a particular workbook. Examples


    include Open (the workbook is opened or created), BeforeSave (the


    workbook is about to be saved), and NewSheet (a new sheet is

    added). VBA code for workbook events must be stored in the

    ThisWorkbook code module.


    n Worksheet events: These occur for a particular worksheet. Examples


    include Change (a cell on the sheet is changed), SelectionChange


    (the cell pointer is moved), and Calculate (the worksheet is recalculated).

    VBA code for worksheet events must be stored in the code module

    for the worksheet (for example, the module named Sheet1).


    n Events not associated with objects: The final category consists of two


    useful application-level events: OnTime and OnKey. These work differently

    from other events.

    «


  • благодарю за обстоятельный ответ


Понравилась статья? Поделить с друзьями:
  • Обновление шрифтов для word
  • Обновления для word 2019
  • Обновление формы vba excel
  • Обновления для word 2013
  • Обновление формул в word