Vba excel cells string

I want to put the cell’s address/name as string rather than column, row.

ws - a worksheet
ows - another worksheet
cell is a string = "G5"
i and c are respectivly row and columns    

cell = ws.Cells(i, 1)

ows.Cells(cell).Value = ws.Cells(i, c)

___________|||||||___________

That code brings out an error.
Cheers, Vihar

asked Jul 24, 2013 at 15:36

Trenera's user avatar

2

Set ws = ThisWorkbook.Sheets("Sheet1")  'Replace with your sheet name
Set ows = ThisWorkbook.Sheets("Sheet2") 'Replace with your sheet name

cell = ws.Cells(i, 1)

ows.Range(cell).Value = ws.Cells(i, c)

Range expects a string, such as «A5» or «A5:B5», where as Cells expects two numbers separated by a comma

 'Examples
 Cells(1,2) 
 Range("A5")
 Range("A5:B5")
 Range(Cells(10,4), Cells(8,3)) 'Use Cells as args for a Range

One other difference is Cells will return either one cell or all cells of a worksheet.

answered Jul 24, 2013 at 15:43

Paul Renton's user avatar

Paul RentonPaul Renton

2,6226 gold badges23 silver badges37 bronze badges

Microsoft Excel cells basically have two values: the formatted value that is shown to the user, and the actual value of the cell. These two values can be extremely different when the cell has certain formatting types such as date, datetime, currency, numbers with commas, etc.

I am writing a script that cleans up database data. It uses find, replace, RegEx, and other functions that act on strings of text. I need to be able to convert data into very specific formats so that my upload tool will accept the data. Therefore I need all of the cells in my Excel spreadsheets to be TEXT. I need the displayed values to match the actual values.

This is surprisingly hard to do in Excel. There is no paste special option that I could find that pastes what you see on your screen as text. «Paste Special -> Values» pastes, predictably, unformatted values. So if you try to «Paste Special -> Values» into cells formatted as TEXT, and they are coming from cells formatted as DATES, you might get something like this:

Old Cell: 4/7/2001

New Cell: 36988

If you paste normally, then the paste goes in as 4/7/2001, but in date format. So if I create a RegEx that looks for 4/7/2001 and changes it to 4/7/01, it will not work, because the underlying value is 36988.

Anyway, I discovered the Cell.Text property and wrote some code that converts all cells in a spreadsheet from formatted to text. But the code has two major problems:

1) It does not work on cells with more than 255 characters. This is because Cell.Text literally displays what the cell is actually showing to the user, and if the column is too narrow, it will display pound signs (########), and columns have a maximum width of 255 characters.

2) It is extremely slow. In my 1.5 million cell test sheet, code execution took 394 seconds.

I’m looking for ideas to optimize the code’s speed, and to make the code work on all display value lengths.

Function ConvertAllCellsToText()

    ' Convert all cells from non-text to text
    ' This is helpful in a variety of ways
        ' Dates and datetimes can now be manipulated by replace, RegEx, etc., since their value is now 4/7/2001 instead of 36988
        ' Phone numbers and zip codes won't get leading zeros deleted if we try to add those

    StartNewTask "Converting all cells to text"

    ' first draft of the code, does not work as intended, dates get scrambled
    'Cells.Select
    'Selection.Copy
    'Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    'Application.CutCopyMode = False

    Dim MyRange As Range
    Set MyRange = ActiveSheet.UsedRange

    ' prevent Cell.Text from being ########
    MyRange.ColumnWidth = 255

    Dim i As Long
    Dim CellText As String
    For Each Cell In MyRange
        If Cell.Text <> Cell.Value And Len(Cell.Value) <= 255 Then
            CellText = Cell.Text
            Cell.NumberFormat = "@"
            Cell.Value = CellText
        End If

        i = i + 1
        If i Mod 2500 = 0 Then
            RefreshScreen
        End If
    Next

    MyRange.ColumnWidth = 20

    ' set all cells to Text format
    Cells.Select
    Selection.NumberFormat = "@"

End Function

Содержание

  1. VBA Excel. Свойства ячейки (объекта Range)
  2. Ячейка и объект Range
  3. Свойства ячейки (объекта Range)
  4. Простые примеры для начинающих
  5. Форматирование ячеек
  6. VBA Ranges — Getting and Setting Cell Values
  7. Getting Cell Values
  8. What happens if you use .Value on a set of cells?
  9. How do you get a single cell from a set of cells?
  10. The Range.Cells Function
  11. Setting Cell Values
  12. How do you set multiple cells’ values?
  13. Getting and Setting Cell Values from a Named Range or Table Name
  14. What’s next?

VBA Excel. Свойства ячейки (объекта Range)

Свойства ячейки, часто используемые в коде VBA Excel. Демонстрация свойств ячейки, как структурной единицы объекта Range, на простых примерах.

Ячейка и объект Range

Объект Range в VBA Excel представляет диапазон ячеек. Он (объект Range) может описывать любой диапазон, начиная от одной ячейки и заканчивая сразу всеми ячейками рабочего листа.

  • Одна ячейка – Range(«A1») .
  • Девять ячеек – Range(«A1:С3») .
  • Весь рабочий лист в Excel 2016 – Range(«1:1048576») .

В VBA Excel есть свойство Cells объекта Range, которое позволяет обратиться к одной ячейке в указанном диапазоне (возвращает объект Range в виде одной ячейки). Если в коде используется свойство Cells без указания диапазона, значит оно относится ко всему диапазону активного рабочего листа.

Примеры обращения к одной ячейке:

  • Cells(1000) , где 1000 – порядковый номер ячейки на рабочем листе, возвращает ячейку «ALL1».
  • Cells(50, 20) , где 50 – номер строки рабочего листа, а 20 – номер столбца, возвращает ячейку «T50».
  • Range(«A1:C3»).Cells(6) , где «A1:C3» – заданный диапазон, а 6 – порядковый номер ячейки в этом диапазоне, возвращает ячейку «C2».

Подробнее о том, как обратиться к ячейке, смотрите в статье: Ячейки (обращение, запись, чтение, очистка).

В этой статье мы рассмотрим свойства объекта Range, применимые, в том числе, к диапазону, состоящему из одной ячейки.

Еще надо добавить, что свойства и методы объектов отделяются от объектов точкой, как в третьем примере обращения к одной ячейке: Range(«A1:C3»).Cells(6) .

Свойства ячейки (объекта Range)

Свойство Описание
Address Возвращает адрес ячейки (диапазона).
Borders Возвращает коллекцию Borders, представляющую границы ячейки (диапазона). Подробнее…
Cells Возвращает объект Range, представляющий коллекцию всех ячеек заданного диапазона. Указав номер строки и номер столбца или порядковый номер ячейки в диапазоне, мы получаем конкретную ячейку. Подробнее…
Characters Возвращает подстроку в размере указанного количества символов из текста, содержащегося в ячейке. Подробнее…
Column Возвращает номер столбца ячейки (первого столбца диапазона). Подробнее…
ColumnWidth Возвращает или задает ширину ячейки в пунктах (ширину всех столбцов в указанном диапазоне).
Comment Возвращает комментарий, связанный с ячейкой (с левой верхней ячейкой диапазона).
CurrentRegion Возвращает прямоугольный диапазон, ограниченный пустыми строками и столбцами. Очень полезное свойство для возвращения рабочей таблицы, а также определения номера последней заполненной строки.
EntireColumn Возвращает весь столбец (столбцы), в котором содержится ячейка (диапазон). Диапазон может содержаться и в одном столбце, например, Range(«A1:A20») .
EntireRow Возвращает всю строку (строки), в которой содержится ячейка (диапазон). Диапазон может содержаться и в одной строке, например, Range(«A2:H2») .
Font Возвращает объект Font, представляющий шрифт указанного объекта. Подробнее о цвете шрифта…
HorizontalAlignment Возвращает или задает значение горизонтального выравнивания содержимого ячейки (диапазона). Подробнее…
Interior Возвращает объект Interior, представляющий внутреннюю область ячейки (диапазона). Применяется, главным образом, для возвращения или назначения цвета заливки (фона) ячейки (диапазона). Подробнее…
Name Возвращает или задает имя ячейки (диапазона).
NumberFormat Возвращает или задает код числового формата для ячейки (диапазона). Примеры кодов числовых форматов можно посмотреть, открыв для любой ячейки на рабочем листе Excel диалоговое окно «Формат ячеек», на вкладке «(все форматы)». Свойство NumberFormat диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковый числовой формат. Если нужно присвоить ячейке текстовый формат, записывается так: Range(«A1»).NumberFormat = «@» . Общий формат: Range(«A1»).NumberFormat = «General» .
Offset Возвращает объект Range, смещенный относительно первоначального диапазона на указанное количество строк и столбцов. Подробнее…
Resize Изменяет размер первоначального диапазона до указанного количества строк и столбцов. Строки добавляются или удаляются снизу, столбцы – справа. Подробнее…
Row Возвращает номер строки ячейки (первой строки диапазона). Подробнее…
RowHeight Возвращает или задает высоту ячейки в пунктах (высоту всех строк в указанном диапазоне).
Text Возвращает форматированный текст, содержащийся в ячейке. Свойство Text диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковое содержимое и один формат. Предназначено только для чтения. Подробнее…
Value Возвращает или задает значение ячейки, в том числе с отображением значений в формате Currency и Date. Тип данных Variant. Value является свойством ячейки по умолчанию, поэтому в коде его можно не указывать.
Value2 Возвращает или задает значение ячейки. Тип данных Variant. Значения в формате Currency и Date будут отображены в виде чисел с типом данных Double.
VerticalAlignment Возвращает или задает значение вертикального выравнивания содержимого ячейки (диапазона). Подробнее…

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

Простые примеры для начинающих

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

Учтите, что в одном программном модуле у всех процедур должны быть разные имена. Если вы уже копировали в модуль подпрограммы с именами Primer1, Primer2 и т.д., удалите их или создайте еще один стандартный модуль.

Форматирование ячеек

Заливка ячейки фоном, изменение высоты строки, запись в ячейки текста, автоподбор ширины столбца, выравнивание текста в ячейке и выделение его цветом, добавление границ к ячейкам, очистка содержимого и форматирования ячеек.

Если вы запустите эту процедуру, информационное окно MsgBox будет прерывать выполнение программы и сообщать о том, что произойдет дальше, после его закрытия.

Источник

VBA Ranges — Getting and Setting Cell Values

In the previous post, we introduced the VBA Range object. This gave us the foundation of working with Ranges in VBA. In today’s post, I’d like to discuss how to get and set cell values through VBA. This will continue to build up our understanding of the VBA Range object and how to use it. There are several ways you can get and set cell values with VBA and I’ll do my best to cover all the necessities, but at the same time keeping it short and to the point. Let’s get started.

Getting Cell Values

To get a cell’s value in VBA, we need to refer to it with the Range object and then call the .Value property.

We’ll use the following spreadsheet for our example. It’s a simple table with some names in it.

To get the value from cell A2 you can use this code snippet:

This will take cell A2 and put it in the variable val . Then we print out the value in the Immediate Window (which the value in our example is Joseph ).

You can also set the range to a variable and access the value from that variable as well:

What happens if you use .Value on a set of cells?

Let’s change our previous code snippet to the following:

If you run this code, you will get an error stating that there is a type mismatch.

What’s going on here?

The problem is that when you work with a set of cells, .Value can only return a single value. So when we ask VBA to return .Value on our variable (which refers to multiple cells), the .Value property doesn’t know which cell we are referring to.

How do you get a single cell from a set of cells?

In order to use .Value to get a value from a cell, we need to refer to a single cell from the range of cells in our variable. The way we do that is with the Cells() VBA function.

The Range.Cells Function

The Cells() function is a way to take a range of cells and return a single cell from the set. Here is the function defined:

Parameter Type Definition
row_number Integer The row number from within the range that you want to refer to.
column_number Integer The column number from within the range that you want to refer to.

Take a look at the following code:

Here we took the range of A2:A5 and referred to row 1 column 1. Since the range variable cellRange refers to A2:A5 , the first row is row 2 and the first column is A .

When using the Cells() function, remember that row 1 and column 1 represent the top-left most cell within the range that the Cells() function is working on. If your range is A1:D5 , then Cells(1, 1) will refer to A1 , but if your range is B2:D6 , then Cells(1, 1) refers to B2 .

Ok, that covers getting cell values from range objects, now let’s discuss setting cell values with range objects.

Does this article help you? If so, please consider supporting me with a coffee ☕️

Setting Cell Values

In order to set a cell’s value, you can use the same .Value property when referring to a cell. In this example, we’ll take A2 ’s value and change it from Joseph to John :

First we set the variable cellRange to A2 . Then we said cellRange.Value = «John» which changes the variable’s .Value property. Remember, though, that the variable is a reference to cell A2 , so whatever you do to that variable, you also do to cell A2 in the worksheet. Finally, we output the value of A2 into the Immediate Window to see that it changed.

We can also see the value changed in the worksheet after we run this code:

How do you set multiple cells’ values?

Remember how I said that you can only read from one cell using .Value ? Well, when setting values, you can actually set multiple cells at one time by using .Value . Take a look at the following code:

If you ran this code, it would set all A2:A5 ’s cells to John :

Well, maybe you’d actually want to do this for some other scenarios, like when you want a bunch of cells to repeat a value.

Let’s take a real example for a second. Let’s say we have two columns, First Name and Last Name . We want to take the Last Name column and place its value after the First Name ’s value; essentially combining the values to make a single Name column.

Here’s our sample data:

Our task is to combine the first and last name columns and place the result in column A . How do we do that?

One solution is to loop through cells A2 through A5 and then set that cell’s value to its own value, plus a space, plus the last name of the cell right next to it.

Sounds easy enough, let’s code it up:

Let’s step through the code.

  • First, we create a variable called names . Then, we set that to range A2:A5 .
  • Next, we create a variable called cell . This is going to be a temporary variable that will change with each iteration of the loop.

Then, we create the loop. Here, we’re looping through the names range object and setting the current item to the cell variable. This means that each time we run through the loop, cell represents a single range object.

*The first time the loop is run, cell is set to A2 . Then, A3 , next A4 , and finally A5 . After that, there are no more cells to go through in the names variable, so the loop ends.

  • I’ll go over how to loop through ranges in a future post since this post is already long enough!

Now we’re ready to combine the first and last names. How we do that is with another Range function called Offset(_rows_, _columns_) . The idea with this function is that if you’re on a cell like A2 and you say cell.Offset(0, 1) what we’re really saying is “move over one column to the right”. This puts us on cell B2 . That’s how we’re able to get the last name in our example.

  • I’ll discuss how to use the Offset() function in more detail in a future post. Again, this post has gone on long enough.

Here are the results of the code after we run it:

From here, we could change the A1 cell to just Name and delete column B altogether.

Getting and Setting Cell Values from a Named Range or Table Name

One last thing I’d like to touch on is when you use the Range() function, you can use a named range or table name instead of a range like A2:A5 . In our first example, our data is in a table named Table1 . To refer to the data of the table, we could use the following:

And to refer to the entire table, we can leverage structured referencesВ like so:

This will return A1 ’s value “Name” since the table starts in A1 .

Also, if you’re new to Excel Tables, click here to learn more.

What’s next?

Honestly, there is so much to discuss with range objects in VBA. I’ll be touching on many more topics regarding ranges in VBA in upcoming posts such as:

  • Modifying cell colors
  • Finding cells by their text values
  • Filtering data
  • Getting the last row in a range (you need this more often than you think)

I’ll come back to this post and put links to these posts as I create them.

If you enjoyed this content, please share and subscribe!

Wow, you read the whole article! You know, people who make it this far are true learners. And clearly, you value learning. Would you like to learn more about Excel? Please consider supporting me by buying me a coffee (it takes a lot of coffee to write these articles!).

Written by Joseph who loves teaching about Excel.

Источник

In this Article

  • Set Cell Value
    • Range.Value & Cells.Value
    • Set Multiple Cells’ Values at Once
    • Set Cell Value – Text
    • Set Cell Value – Variable
  • Get Cell Value
    • Get ActiveCell Value
    • Assign Cell Value to Variable
  • Other Cell Value Examples
    • Copy Cell Value
    • Compare Cell Values

This tutorial will teach you how to interact with Cell Values using VBA.

Set Cell Value

To set a Cell Value, use the Value property of the Range or Cells object.

Range.Value & Cells.Value

There are two ways to reference cell(s) in VBA:

  • Range Object – Range(“A2”).Value
  • Cells Object – Cells(2,1).Value

The Range object allows you to reference a cell using the standard “A1” notation.

This will set the range A2’s value = 1:

Range("A2").Value = 1

The Cells object allows you to reference a cell by it’s row number and column number.

This will set range A2’s value = 1:

Cells(2,1).Value = 1

Notice that you enter the row number first:

Cells(Row_num, Col_num)

Set Multiple Cells’ Values at Once

Instead of referencing a single cell, you can reference a range of cells and change all of the cell values at once:

Range("A2:A5").Value = 1

Set Cell Value – Text

In the above examples, we set the cell value equal to a number (1).  Instead, you can set the cell value equal to a string of text.  In VBA, all text must be surrounded by quotations:

Range("A2").Value = "Text"

If you don’t surround the text with quotations, VBA will think you referencing a variable…

Set Cell Value – Variable

You can also set a cell value equal to a variable

Dim strText as String
strText = "String of Text"

Range("A2").Value = strText

Get Cell Value

You can get cell values using the same Value property that we used above.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Get ActiveCell Value

To get the ActiveCell value and display it in a message box:

MsgBox ActiveCell.Value

Assign Cell Value to Variable

To get a cell value and assign it to a variable:

Dim var as Variant

var = Range("A1").Value

Here we used a variable of type Variant. Variant variables can accept any type of values.  Instead, you could use a String variable type:

Dim var as String

var = Range("A1").Value

A String variable type will accept numerical values, but it will store the numbers as text.

If you know your cell value will be numerical, you could use a Double variable type (Double variables can store decimal values):

Dim var as Double

var = Range("A1").Value

However, if you attempt to store a cell value containing text in a double variable, you will receive an type mismatch error:

get cell value assign variable

Other Cell Value Examples

VBA Programming | Code Generator does work for you!

Copy Cell Value

It’s easy to set a cell value equal to another cell value (or “Copy” a cell value):

Range("A1").Value = Range("B1").Value

You can even do this with ranges of cells (the ranges must be the same size):

Range("A1:A5").Value = Range("B1:B5").Value

Compare Cell Values

You can compare cell values using the standard comparison operators.

Test if cell values are equal:

MsgBox Range("A1").Value = Range("B1").Value

Will return TRUE if cell values are equal. Otherwise FALSE.

You can also create an If Statement to compare cell values:

If Range("A1").Value > Range("B1").Value Then

  Range("C1").Value = "Greater Than"

Elseif Range("A1").Value = Range("B1").Value Then

  Range("C1").Value = "Equal"

Else

  Range("C1").Value = "Less Than"

End If

You can compare text in the same way (Remember that VBA is Case Sensitive)

  • If you would like to post, please check out the MrExcel Message Board FAQ and register here. If you forgot your password, you can reset your password.

  • Thread starter

    SpearC1993

  • Start date

    Feb 19, 2016

  • #1

Hello all,

Back again for another question!

Can I use a cell value in VBA to open a file for example:

Set January = Workbooks.Open(«C:Users»CELL A1 HERE».xls») <- this is a guess

In my work sheet have a cell like such

The result would then be that the macro would open an excel in the location «C:UsersJanuary_3047.xls». At the moment I have statically written these in but I dont want to write over this code every month.

Which came first: VisiCalc or Lotus 1-2-3?

Dan Bricklin and Bob Frankston debuted VisiCalc in 1979 as a Visible Calculator. Lotus 1-2-3 debuted in the early 1980’s, from Mitch Kapor.

  • #2

Try this, adjusting ‘Sheetname’ to the name of the sheet where A1 holds your bookname.

Code:

Dim MyBook As String
MyBook = Sheets("Sheetname").Range("A1").Value
Set January = Workbooks.Open("C:Users" & MyBook & ".xls")

  • #3

Thank you! Such a quick response, thank you very much :)

James006

DanteAmor

Threads
1,192,596
Messages
5,993,418
Members
440,485
Latest member
nicfurley

Excel VBA CSTR Function

CSTR in VBA is a data type conversion function that one may use to convert any value provided to this function to a string. For example, even if the given input is an integer or float value, this function will convert the value’s data type to a string data type, so the return type of this function is a string.

How do we go about this if we need to convert any value to string data type in VBAData type is the core character of any variable, it represents what is the type of value we can store in the variable and what is the limit or the range of values which can be stored in the variable, data types are built-in VBA and user or developer needs to be aware which type of value can be stored in which data type. Data types assign to variables tells the compiler storage size of the variable.read more? For this, in VBA, we have a function called “CSTR.” In this article, we will guide you through the methodology of the “CSTR” function in VBA.

The String is the data type that holds any String values. When we say string, it generally refers to text values, but that is not true with VBA codingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more. A string can hold any order of characters as data. For example, “Hello” is treated as String, “123456” is treated as a string and “12-04-2019” as a string. This String data type can hold any order of characters.

Table of contents
  • Excel VBA CSTR Function
    • What Does CSTR Function Do in VBA?
      • VBA CSTR Syntax
    • How to Use VBA CSTR Function in Excel?
      • Example #1
      • Example #2
      • Example #3
    • Recommended Articles

VBA CSTR

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA CSTR (wallstreetmojo.com)

What Does CSTR Function Do in VBA?

Have you ever thought of converting a different expression to Strings in VBAString functions in VBA do not replace the string; instead, this function creates a new string. There are numerous string functions in VBA, all of which are classified as string or text functions.read more? If you have a doubt, is that possible? Then the answer is an absolute YES!

CSTR is a function covering different format expressions to String format in VBA. With the CSTR function, we can convert the provided expression value to the String data type.

VBA CSTR Syntax

Below is the syntax of the Excel VBA CSTR function.

cstr formula

The syntax of the CSTR function includes only one argument.

Expression: It is the targeted value or cell value we are trying to change to the String data type.

The value could be any data type. So, CSTR goes ahead and converts to String data type. The common data types we usually convert are Integer, Boolean, and Date to String data types.

How to Use VBA CSTR Function in Excel?

Now, we will see some examples of the Excel VBA CSTR function.

You can download this VBA CStr Excel Template here – VBA CStr Excel Template

Example #1

Look at the below code.

Code:

Sub CSTR_Example1()

Dim NumericValue As Integer
Dim StringResult As String

NumericValue = 855

StringResult = CStr(NumericValue)

MsgBox StringResult

End Sub

cstr example 1.1

Firstly, we assigned the Integer data type to the variable “NumericValue” as 855. Now, the variable “NumericValue” holds the Integer data type. Another variable, “StringResult,” assigned the formula CSTR to convert Integer data type to String data type.

CSTR converted the integer number to String data type. So, even though we can see the number 855, it is no longer an Integer Date Type in VBAIn VBA, an integer is a data type that may be assigned to any variable and used to hold integer values. In VBA, the bracket for the maximum number of integer variables that can be kept is similar to that in other languages. Using the DIM statement, any variable can be defined as an integer variable.read more. Instead, it is now in the String data type.

cstr example 1.2

Example #2

Look at an example of VBA Boolean Data TypeBoolean is an inbuilt data type in VBA used for logical references or logical variables. The value this data type holds is either TRUE or FALSE and is used for logical comparison. The declaration of this data type is similar to all the other data types.read more Conversion.

Code:

Sub CSTR_Example2()

Dim Val1 As Boolean
Dim Val2 As Boolean

Val1 = True
Val2 = False

MsgBox CStr(Val1) & vbNewLine & CStr(Val2)

End Sub

example 1.3

In the above code, I have declared two variables as Boolean.

Dim Val1 As Boolean

Dim Val2 As Boolean

In the next line, we have assigned Boolean values as TRUE and FALSE.

Val1 = True

Val2 = False

At this point, both variables are Boolean data types. Therefore, we have applied the VBA CSTR function in this example to convert this Boolean data type to a String data type.

example 2.2

Example #3

Look at the example of Date data type conversion to String data type.

Code:

Sub CSTR_Example3()

Dim Date1 As Date
Dim Date2 As Date

Date1 = #10/12/2019#
Date2 = #5/14/2019#

MsgBox CStr(Date1) & vbNewLine & CStr(Date2)

End Sub

VBA cstr example 3.1

We have declared two variables as Date.

Dim Date1 As Date

Dim Date2 As Date

Next line, we have assigned the Date values as 10-12-2019 and 05-14-2019, respectively.

Date1 = #10/12/2019#

Date2 = #5/14/2019#

At this point, both the variables are Date data types. In the next line, we have applied the CSTR function to convert the Date data type to the String data type. Like CSTR function used to convert any other data type to String data type.

example 3.2

Recommended Articles

This article has been a guide to VBA CStr. Here, we learn how to use the VBA CStr function to convert the value to String data type, along with some simple to advanced examples. Below are some useful Excel articles related to VBA: –

  • Convert String in VBA
  • Excel VBA StrComp
  • VBA Like Operator
  • Count Function in VBA
  • Remove From My Forums
  • Question

  • I’m a complete novice with VBA, so hopefully this won’t be too difficult for someone in the know.  I’m trying to read the text from a cell in Excel (a PLC tagname) into a variable in VBA, then use the string variable to read that tag from the PLC. 
    I’ve successfully used the DDERequest instruction to read known tagnames from the PLC, but I now want to be able to read variable tagnames from cells in Excel, but the line TagName = Cells(«i», «D»).Value
    returns runtime error 13, type mismatch.  Can anyone advise the error I’m making?  The tagname text is in column D, starting at row (i).  I’ve also tried TagName = Cells(«i», «D»).Text,
    but get the same error.

    Private Sub CommandButton1_Click()

        rslinx = OpenRSLinx() ‘Open connection to RSlinx

        Dim LENGTH As Long
        Dim TagName As String
        LENGTH = Cells(1, «B»).Value

        ‘Loop through reading the CLX tags and
        ‘put the values into cells
        For i = 2 To (LENGTH + 2)
            ‘Read TagName
            TagName = Cells(«i», «D»).Value
            ‘Read Tag Value
            ‘Get the value from the DDE link
            TagValue = DDERequest(rslinx, «TagName,L1,C1»)

            ‘If there is an error, display a message box
            If TypeName(TagValue) = «Error» Then
                If MsgBox(«Error reading Parameter[» & i & «] » & _
                    «Continue with Read?», vbYesNo + vbExclamation, _
                    «Error») = vbNo Then Exit For
            Else
                ‘No error, place data in cell
                Cells(2 + i, 5) = TagValue
            End If

        Next i

        ‘Terminate the DDE connection
        DDETerminate rslinx

    End Sub

                               

Answers

  • Hello Roksan,

    Please try

    TagName = Cells(i, "D").Value

    Best Regards,

    Terry


    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
    MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by

      Friday, July 27, 2018 12:54 PM

Функции преобразования типов данных в VBA Excel. Наименования функций, синтаксис, типы возвращаемых данных, диапазоны допустимых значений выражения-аргумента.

Синтаксис функций преобразования

Выражение (аргумент) – это любое строковое или числовое выражение, возвращающее значение, входящее в диапазон допустимых значений для аргумента. Выражение может быть представлено переменной или другой функцией.

Если аргумент, переданный в функцию, не входит в диапазон типа, в который преобразуются данные, происходит ошибка.

Функции преобразования типов

Наименования функций преобразования типов, типы возвращаемых данных, диапазоны допустимых значений для аргумента:

Функция Тип данных Диапазон значений аргумента
CBool Boolean Любое допустимое строковое или числовое выражение.
CByte Byte От 0 до 255.
CCur Currency От -922 337 203 685 477,5808 до 922 337 203 685 477,5807.
CDate Date Любое допустимое выражение даты.
CDbl Double От -1,79769313486231E308 до -4,94065645841247E-324 для отрицательных значений; от 4,94065645841247E-324 до 1,79769313486232E308 для положительных значений.
CDec Decimal 79 228 162 514 264 337 593 543 950 335 для чисел без десятичных знаков. Для чисел с 28 десятичными знаками диапазон составляет 7,9228162514264337593543950335. Наименьшим возможным числом, отличным от нуля, является число 0,0000000000000000000000000001.
CInt Integer От -32 768 до 32 767, дробная часть округляется.
CLng Long От -2 147 483 648 до 2 147 483 647, дробная часть округляется.
CSng Single От -3,402823E38 до -1,401298E-45 для отрицательных значений; от 1,401298E-45 до 3,402823E38 для положительных значений.
CStr String Результат, возвращаемый функцией CStr, зависит от аргумента Выражение.
CVar Variant Диапазон совпадает с типом Double  для числовых значений и с типом  String  для нечисловых значений.

Дополнительно для VBA7:

Функция Тип данных Диапазон значений аргумента
CLngLng LongLong От -9 223 372 036 854 775 808 до 9 223 372 036 854 775 807, дробная часть округляется. Действительно только для 64-разрядных платформ.
CLngPtr LongPtr От -2 147 483 648 до 2 147 483 647 для 32-разрядных платформ, от -9 223 372 036 854 775 808 до 9 223 372 036 854 775 807 для 64-разрядных платформ, дробная часть округляется в обоих типах систем.

Примеры преобразования типов

Функция CBool

Функция CBool используется для преобразования выражений в тип данных Boolean.

Dim a

a = CBool(10) ‘Результат: True

a = CBool(0) ‘Результат: False

a = CBool(«True») ‘Результат: True

a = CBool(«Test») ‘Результат: Error

Dim a, b, c

a = «Test1»

b = «Test2»

c = CBool(a = b) ‘Результат: False

c = CBool(a <> b) ‘Результат: True

Функция CByte

Функция CByte используется для преобразования выражений в тип данных Byte.

Dim a, b, c

a = 654

b = 3.36

c = a / b ‘Результат: 194,642857142857

c = CByte(c) ‘Результат: 195

c = a * b ‘Результат: 2197,44

c = CByte(c) ‘Результат: Error

Функция CCur

Функция CCur используется для преобразования выражений в тип данных Currency.

Dim a, b, c

a = 254.6598254

b = 569.2156843

c = a + b ‘Результат: 823,8755097

c = CCur(a + b) ‘Результат: 823,8755

Функция CDate

Функция CDate используется для преобразования выражений в тип данных Date. Она распознает форматы даты в соответствии с национальной настройкой системы.

Dim a As String, b As Date, c As Double

a = «28.01.2021»

b = CDate(a) ‘Результат: #28.01.2021#

c = CDbl(b) ‘Результат: 44224

Dim a

a = CDate(44298.63895) ‘Результат: #12.04.2021 15:20:05#

a = CDate(44298) ‘Результат: #12.04.2021#

a = CDate(0.63895) ‘Результат: #15:20:05#

Функция CDbl

Функция CDbl используется для преобразования выражений в тип данных Double.

Dim a As String, b As String, c As Double

a = «45,3695423»

b = «548955,756»

c = CDbl(a) + CDbl(b) ‘Результат: 549001,1255423

Примечание
Eсли основной язык системы – русский, при записи в редакторе VBA Excel дробного числа в виде текста, ставим в качестве разделителя десятичных разрядов – запятую. Проверьте разделитель по умолчанию для своей национальной системы:
MsgBox Application.DecimalSeparator

Функция CDec

Функция CDec используется для преобразования выражений в тип данных Decimal.

Dim a As String, b As Double, c

a = «5,9228162514264337593543950335»

b = 5.92281625142643

c = CDec(a) CDec(b) ‘Результат: 0,0000000000000037593543950335

Dim a As Double, b As String, c

a = 4.2643E14

b = CStr(a) ‘Результат: «4,2643E-14»

c = CDec(a) ‘Результат: 0,000000000000042643

Функция CInt

Функция CInt используется для преобразования выражений в тип данных Integer.

Dim a As String, b As Integer

a = «2355,9228»

b = CInt(a) ‘Результат: 2356

Функция CLng

Функция CLng используется для преобразования выражений в тип данных Long.

Dim a As Date, b As Long

a = CDate(44298.63895) ‘Результат: #12.04.2021 15:20:05#

b = CLng(a) ‘Результат: 44299

a = CDate(b) ‘Результат: #13.04.2021#

Функция CSng

Функция CSng используется для преобразования выражений в тип данных Single.

Dim a As String, b As Single

a = «3,2365625106»

b = CSng(a) ‘Результат: 3,236562

Функция CStr

Функция CStr используется для преобразования выражений в тип данных String.

Dim a As Single, b As String

a = 5106.23

b = CStr(a) ‘Результат: «5106,23»

Функция CVar

Функция CVar используется для преобразования выражений в тип данных Variant.

Dim a As Double, b As String, c

a = 549258.232546

b = «Новое сообщение»

c = CVar(a) ‘Результат: 549258,232546 (Variant/Double)

c = CVar(b) ‘Результат: «Новое сообщение» (Variant/String)

Функции преобразования типов данных используются в тексте процедур VBA Excel для того, чтобы указать, что результатом выполнения той или иной операции должны стать данные определенного типа, отличающегося от типа, заданного по умолчанию.


Понравилась статья? Поделить с друзьями:
  • Vba excel cells rows count 1 end xlup row
  • Vba excel cells formula
  • Vba excel cells find what
  • Vba excel cell диапазон
  • Vba excel cell column