Перевести формулу excel vba

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Может быть я и «открыл Америку», но всё-таки расскажу, а вдруг кому-нибудь понадобится…  

  Разбираясь с методами программной работы с буфером обмена, случайно выяснил, что при программном копировании формулы из ячейки листа, в буфере обмена она оказывается записана в английской нотации, т.е. в виде, готовом для применения формулы листа в коде VBA.  
Т.е. пусть, к примеру, нам нужно в процедуре VBA выполнить какое-то вычисление, которое достаточно просто выполняется формулами листа. Но для того, чтобы процедура VBA поняла, что мы от неё хотим, необходимо вункцию листа вводить в код в английской нотации, что при сложных формулах вызывает затруднения.  
Есть простой метод перевода.  
1. В любом модуле книги пишем код:  
Sub GetFormula_For_VBA() ‘ скопировать в буфер обмена формулу из ActiveCell, готовую для вставки в код VBA  
  With GetObject(«New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}»)  
      .SetText ActiveCell.Formula : .PutInClipboard  
  End With  
End Sub  

  2. В любой ячейке листа книги пишем и отлаживаем свою формулу.  
К примеру, я написАл и отладил в ячейке M2 формулу:  
=ЕСЛИ($L2=»»;»»;ВПР($L2;’Узлы СВЯЗИ’!$B:$P;10;0))  

  3. Выделяем ячейку M2 и запускаем макрос GetFormula_For_VBA  
После его работы в буфере обмена окажется формула:  
=IF($L2=»»,»»,VLOOKUP($L2,’Узлы МВОС’!$B:$P,10,0))  
Т.е. произошёл автоматический перевод нотации формулы с РУС на ENG. А такую формулу уже не сложно встроить в код макроса.

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

You need 2 changes:

(1) To use a function in VBA when it is available in native Excel, you need to preface each function with Application.WorksheetFunction. ie:

x = Application.WorksheetFunction.Sum(y,z)

(2) To reference a cell within a sheet, in VBA, you need to access it specifically, in one of a few ways. The simplest for our purposes is the RANGE property, as follows:

x = Application.WorksheetFunction.Sum(Range("A1:A2"))

So to put those two changes together, your formula would look like this:

=Application.WorksheetFunction.INDEX(Range("$D$2:$D$1112",Application.WorksheetFunction.MATCH(1,(RANGE("$A$2:$A$1112"=RANGE("$U$7")*(Range("$C$2:$C$1112"=Range("$W$7")*(Range("$B$2:$B$1112"=Range("F3"),0))

Although I see now having gone through this that you seem to be using an Array Formula — not sure if any special jigging is required to get that to work.

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Application.ConvertFormula method (Excel)

vbaxl10.chm133097

vbaxl10.chm133097

excel

Excel.Application.ConvertFormula

6ed0a76c-9db5-f6ab-a91d-d4e1b6674c53

04/04/2019

medium

Application.ConvertFormula method (Excel)

Converts cell references in a formula between the A1 and R1C1 reference styles, between relative and absolute references, or both. Variant.

Syntax

expression.ConvertFormula (Formula, FromReferenceStyle, ToReferenceStyle, ToAbsolute, RelativeTo)

expression A variable that represents an Application object.

Parameters

Name Required/Optional Data type Description
Formula Required Variant A string that contains the formula that you want to convert. This must be a valid formula, and it must begin with an equal sign.
FromReferenceStyle Required XlReferenceStyle The reference style of the formula.
ToReferenceStyle Optional Variant A constant of XlReferenceStyle specifying the reference style that you want returned. If this argument is omitted, the reference style isn’t changed; the formula stays in the style specified by FromReferenceStyle.
ToAbsolute Optional Variant A constant of XlReferenceType that specifies the converted reference type. If this argument is omitted, the reference type isn’t changed.
RelativeTo Optional Variant A Range object that contains one cell. Relative references relate to this cell.

Return value

Variant

Remarks

There is a 255 character limit for the formula.

Example

This example converts a SUM formula that contains R1C1-style references to an equivalent formula that contains A1-style references, and then it displays the result.

inputFormula = "=SUM(R10C2:R15C2)" 
MsgBox Application.ConvertFormula( _ 
 formula:=inputFormula, _ 
 fromReferenceStyle:=xlR1C1, _ 
 toReferenceStyle:=xlA1)

[!includeSupport and feedback]

Since sample data is not available therefore I’m assuming,,

  • Sheet 1 Column O, Names to be searched in O2:O10.
  • Sheet 2 has Clasification & Names, are Named range in A2:A10 & B2:B10.
  • You need results in range P2:P10 in Sheet1.

Now first, I would like to suggest how to assign Excel Formula to VBA code.

Range("P2").FormulaArray = "=IFERROR(INDEX(Clasification,MATCH(TRUE,ISNUMBER(SEARCH(Names,O2)),0)),""No Found"")"

N.B. You need an Array (CSE) formula so that .FormulaArray has been used.


But since Named Range is/are need to be declared while using with VBA Macro, therefore I would like to recommend you the following code to use as Standard Module.

Sub Formula()

Dim Clasification As Range
Dim Names As Range


 Set Clasification = Sheets("Sheet2").Range("A2:A10")
 Set Names = Sheets("Sheet2").Range("B2:B10")


Range("P2").FormulaArray = "=IFERROR(INDEX(Clasification,MATCH(TRUE,ISNUMBER(SEARCH(Names,O2)),0)),""No Found"")"
Range("P2:P10").FillDown
End Sub

Adjust cell references & Named Ranges in the code as needed.

Printing values instead of the formulas themselves can help protect your IP or prevent users from changing them. In this article, we’re going to show you how to have Excel convert formula to value using VBA.

How to have Excel convert formula to value

We can check each cell using a For Each…Next loop. Below you will find 3 examples using the loop that check cells in a selected area, in the entire worksheet, and all worksheets in a workbook.

After identifying the cells, we can check whether they contain formulas using the HasFormula property. This returns a Boolean value. If the HasFormula returns TRUE, then our code overwrites the formula by setting the cell value into the Formula property of the cell.

rng.Formula = rng.Value

First, you need to add the module into the workbook or the add-in file. Copy and paste the code into the module to run it. The main advantage of the module method is that it allows saving the code in the file, so that it can be used again later. Furthermore, the subroutines in modules can be used by icons in the menu ribbons or keyboard shortcuts. Remember to save your file in either XLSM or XLAM format to save your VBA code.

Convert formulas to values in a selected range

Sub ConvertFormulasToValuesInSelection()

    Dim rng As Range

    For Each rng In Selection

        If rng.HasFormula Then

            rng.Formula = rng.Value

        End If

    Next rng

End Sub

Convert formulas to values in active worksheet

Sub ConvertFormulasToValuesInActiveWorksheet()

    Dim rng As Range

    For Each rng In ActiveSheet.UsedRange

        If rng.HasFormula Then

            rng.Formula = rng.Value

        End If

    Next rng

End Sub

Convert formulas to values in all worksheets

Sub ConvertFormulasToValuesAllWorksheets()

    Dim ws As Worksheet, rng As Range

    For Each ws In ActiveWorkbook.Worksheets

        For Each rng In ws.UsedRange

            If rng.HasFormula Then

                rng.Formula = rng.Value

            End If

        Next rng

    Next ws

End Sub

Like this post? Please share to your friends:
  • Перевести формат телефонов в excel
  • Перевод jpeg в word текст
  • Перевести формат времени в минуты excel
  • Перевод jpeg в word онлайн с возможностью редактирования
  • Перевести формат word в adobe