Vba excel textbox формат даты

  • Remove From My Forums
  • Question

  • dears

    good greeting

    how can format date by automatic way just when i’m write it inside textbox excel userform vba

    regards…….

Answers

  • Hello TAREK SHARAF,

    Textbox in useform does not have format property, you could format its text content in AfterUpated event.

    Here is the simply code and demonstration.

    Private Sub TextBox1_AfterUpdate()
    If IsDate(Me.TextBox1.Text) Then
    Me.TextBox1.Text = Format(Me.TextBox1.Text, "dd/mm/yyyy")
    End If
    End Sub
    
    

    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

      Tuesday, February 27, 2018 4:48 AM

  • Hi,

    It is hard to change date format automatically by handling every single key-input in a TextBox.
    And I’m afraid you forget what date format should be used.
    So, I made a button [Change Format] that changed date format according to selected an option button (radio button).    

    Here’s my code:

    ' ---[Change Format] button
    Private Sub btn_ChangeFormat_Click()
        If (Len(TextBox1.Text) < 8) _
            Or (InStr(TextBox1.Text, "/") < 2) Then
            MsgBox "invalid date value"
            Exit Sub
        End If
        ' ---------------
        If (rbt_YMD_S.Value = True) Then
            TextBox1.Text = Format(TextBox1.Text, "yyyy/M/d")
        End If
        If (rbt_DMY_S.Value = True) Then
            TextBox1.Text = Format(TextBox1.Text, "d/M/yyyy")
        End If
        If (rbt_MDY_S.Value = True) Then
            TextBox1.Text = Format(TextBox1.Text, "M/d/yyyy")
        End If
        ' ---------------
        If (rbt_YMD_L.Value = True) Then
            TextBox1.Text = Format(TextBox1.Text, "yyyy/MMM/dd")
        End If
        If (rbt_DMY_L.Value = True) Then
            TextBox1.Text = Format(TextBox1.Text, "dd/MMM/yyyy")
        End If
        If (rbt_MDY_L.Value = True) Then
            TextBox1.Text = Format(TextBox1.Text, "MMM/dd/yyyy")
        End If
    End Sub

    Regards,


    Ashidacchi

    • Edited by
      Ashidacchi
      Tuesday, February 27, 2018 3:50 AM
    • Marked as answer by
      TAREK SHARAF
      Tuesday, February 27, 2018 4:48 AM

I too, one way or another stumbled on the same dilemma, why the heck Excel VBA doesn’t have a Date Picker. Thanks to Sid, who made an awesome job to create something for all of us.

Nonetheless, I came to a point where I need to create my own. And I am posting it here since a lot of people I’m sure lands on this post and benefit from it.

What I did was very simple as what Sid does except that I do not use a temporary worksheet. I thought the calculations are very simple and straight forward so there’s no need to dump it somewhere else. Here’s the final output of the calendar:

enter image description here

How to set it up:

  • Create 42 Label controls and name it sequentially and arranged left to right, top to bottom (This labels contains greyed 25 up to greyed 5 above). Change the name of the Label controls to Label_01,Label_02 and so on. Set all 42 labels Tag property to dts.
  • Create 7 more Label controls for the header (this will contain Su,Mo,Tu…)
  • Create 2 more Label control, one for the horizontal line (height set to 1) and one for the Month and Year display. Name the Label used for displaying month and year Label_MthYr
  • Insert 2 Image controls, one to contain the left icon to scroll previous months and one to scroll next month (I prefer simple left and right arrow head icon). Name it Image_Left and Image_Right

The layout should be more or less like this (I leave the creativity to anyone who’ll use this).

enter image description here

Declaration:
We need one variable declared at the very top to hold the current month selected.

Option Explicit
Private curMonth As Date

Private Procedure and Functions:

Private Function FirstCalSun(ref_date As Date) As Date
    '/* returns the first Calendar sunday */
    FirstCalSun = DateSerial(Year(ref_date), _
                  Month(ref_date), 1) - (Weekday(ref_date) - 1)
End Function

Private Sub Build_Calendar(first_sunday As Date)
    '/* This builds the calendar and adds formatting to it */
    Dim lDate As MSForms.Label
    Dim i As Integer, a_date As Date

    For i = 1 To 42
        a_date = first_sunday + (i - 1)
        Set lDate = Me.Controls("Label_" & Format(i, "00"))
        lDate.Caption = Day(a_date)
        If Month(a_date) <> Month(curMonth) Then
            lDate.ForeColor = &H80000011
        Else
            If Weekday(a_date) = 1 Then
                lDate.ForeColor = &HC0&
            Else
                lDate.ForeColor = &H80000012
            End If
        End If
    Next
End Sub

Private Sub select_label(msForm_C As MSForms.Control)
    '/* Capture the selected date */
    Dim i As Integer, sel_date As Date
    i = Split(msForm_C.Name, "_")(1) - 1
    sel_date = FirstCalSun(curMonth) + i

    '/* Transfer the date where you want it to go */
    MsgBox sel_date

End Sub

Image Events:

Private Sub Image_Left_Click()

    If Month(curMonth) = 1 Then
        curMonth = DateSerial(Year(curMonth) - 1, 12, 1)
    Else
        curMonth = DateSerial(Year(curMonth), Month(curMonth) - 1, 1)
    End If

    With Me
        .Label_MthYr.Caption = Format(curMonth, "mmmm, yyyy")
        Build_Calendar FirstCalSun(curMonth)
    End With

End Sub

Private Sub Image_Right_Click()

    If Month(curMonth) = 12 Then
        curMonth = DateSerial(Year(curMonth) + 1, 1, 1)
    Else
        curMonth = DateSerial(Year(curMonth), Month(curMonth) + 1, 1)
    End If

    With Me
        .Label_MthYr.Caption = Format(curMonth, "mmmm, yyyy")
        Build_Calendar FirstCalSun(curMonth)
    End With

End Sub

I added this to make it look like the user is clicking the label and should be done on the Image_Right control too.

Private Sub Image_Left_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
                                 ByVal X As Single, ByVal Y As Single)
    Me.Image_Left.BorderStyle = fmBorderStyleSingle
End Sub

Private Sub Image_Left_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)
    Me.Image_Left.BorderStyle = fmBorderStyleNone
End Sub

Label Events:
All of this should be done for all 42 labels (Label_01 to Lable_42)
Tip: Build the first 10 and just use find and replace for the remaining.

Private Sub Label_01_Click()
    select_label Me.Label_01
End Sub

This is for hovering over dates and clicking effect.

Private Sub Label_01_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)
    Me.Label_01.BorderStyle = fmBorderStyleSingle
End Sub

Private Sub Label_01_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)
    Me.Label_01.BackColor = &H8000000B
End Sub

Private Sub Label_01_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _
                             ByVal X As Single, ByVal Y As Single)
    Me.Label_01.BorderStyle = fmBorderStyleNone
End Sub

UserForm Events:

Private Sub UserForm_Initialize()
    '/* This is to initialize everything */
    With Me
        curMonth = DateSerial(Year(Date), Month(Date), 1)
        .Label_MthYr = Format(curMonth, "mmmm, yyyy")
        Build_Calendar FirstCalSun(curMonth)
    End With

End Sub

Again, just for the hovering over dates effect.

Private Sub UserForm_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)

    With Me
        Dim ctl As MSForms.Control, lb As MSForms.Label

        For Each ctl In .Controls
            If ctl.Tag = "dts" Then
                Set lb = ctl: lb.BackColor = &H80000005
            End If
        Next
    End With

End Sub

And that’s it. This is raw and you can add your own twist to it.
I’ve been using this for awhile and I have no issues (performance and functionality wise).
No Error Handling yet but can be easily managed I guess.
Actually, without the effects, the code is too short.
You can manage where your dates go in the select_label procedure. HTH.

 

Andrey Ka

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

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

#1

10.02.2022 02:46:31

Знатоки, доброго времени суток.

Необходима ваша помощь, имеется рабочий код который своим умом не доработать, работает корректно показывает дату, только не удобно в чтении (ММ.ДД.ГГГГ), путаница, соответственно хочется получить результат к которому в основном все привыкли (ДД.ММ.ГГГГ).

Код
Private Sub UserForm_Activate()

UserForm1.TextBox1.Value = Worksheets("Control Menu").Cells(1, 1).Value 'Показывает ММ.ДД.ГГГГ, надо ДД.ММ.ГГГГ
UserForm1.TextBox2.Value = Worksheets("Control Menu").Cells(2, 1).Value 'Показывает ММ.ДД.ГГГГ, надо ДД.ММ.ГГГГ
UserForm1.TextBox3.Value = Worksheets("Control Menu").Cells(3, 1).Value 'Показывает ММ.ДД.ГГГГ, надо ДД.ММ.ГГГГ

End Sub

Спасибо!

 

Иван Бунев

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

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

#2

10.02.2022 06:27:11

Попробуй вот так:

Код
UserForm1.TextBox2.Value = Worksheets("Control Menu").Cells(2, 1).Value = date
 

Andrey Ka

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

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

При такой комбинации в TextBox1,2,3 отображается True или False

Изменено: Andrey Ka10.02.2022 06:50:28

 

БМВ

Модератор

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

Excel 2013, 2016

#4

10.02.2022 07:59:44

Цитата
Иван Бунев написал:
Попробуй вот так:

А что по вашему означает эта запись?
Andrey Ka, Что в ячейках?

По вопросам из тем форума, личку не читаю.

 

webley

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

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

#5

10.02.2022 09:02:28

Код
UserForm1.TextBox1.Value = Format(Worksheets("Control Menu").Cells(1, 1).Value, "dd.MM.yyyy")
 

sokol92

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

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

Коллеги, используйте при присвоении текста элементу управления       Textbox свойство Text, а не Value. Не берите сомнительные

примеры

.

В сообщении #1 замените TextBox1.Value на TextBox1.Text и т.д.

 

Andrey Ka

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

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

#7

11.02.2022 00:26:49

webley

, спасибо, работает.

Изменено: Andrey Ka11.02.2022 00:27:19

Excel VBA Tutorial 5 - Text Box Properties, Text Box Currency Format and Date Format

In Excel VBA tutorial 4 we learned how to add different tools to the user form. In today’s tutorials, we will learn about the properties of text boxes. We will learn about different formats of text boxes.

About User Form Properties In Tutorial 3, we saw some important points. In the same way every tool has its properties. Some tabs are more or less according to the tool.

Excel VBA Tutorial 5 - Text Box Properties, Text Box Currency Format and Date Format

1. Name – Any name can be given to the text box.

2. Text box Size – Option of drag and drop with the mouse is better to increase the size or more.

3. Control Tip Text – When the application is run, you have to type the text in the control tip text to show a text tip as soon as the mouse cursor is moved over the text box.

Excel VBA Tutorial 5 - Text Box Properties, Text Box Currency Format and Date Format

4. Enable – Many times the project has to show the text in the text box, but to ban it from editing, Select False Option in the option of enable, no user can edit the text of the text box.

5. Visible – To hide the text box, the text box will be hidden as soon as it is false in front of the Visible option.

6. Text – To show any text by default in the text box, you can type the words type in front of the text option.

7. With the option of Text Align, Back Color, Border Color, you can change the design of the text box.

8. Password Character – Type one of the special characters in the password char to show the text * or # or @ of the text box as such.

For example – When typing a text box password, all we need to do is to show * star *, type password Char  *  .

Excel VBA Tutorial 5 - Text Box Properties, Text Box Currency Format and Date Format

How to change the text box format?

1. Text box currency format

To change the text box Value to currency format, double click on the text box or right click to view code.

Private Sub TextBox1_Change() 

End Sub

The text box name and change will appear. That means, while making any change in the text box, we can give the command in it. You can see multiple options in the drop down option by clicking above the change option above. We will be able to make any changes according to the behavior of the text box. We have to type the code of the format in the line below Private Sub TextBox1_Change ().

Excel VBA Tutorial 5 - Text Box Properties, Text Box Currency Format and Date Format

Private Sub TextBox1_Change()

Me.TextBox1.Text = Format(Me.TextBox1, “####,##”)

End Sub

Now run the project by pressing F5. And type any number in the text box. The value will be converted to currency format only while typing.

If you need a decimal number in the currency format, then click on the text Behavior After Update

Me.TextBox1.Text = Format (Me.TextBox1, “####, ##. 00”) Apply this code.

Private Sub TextBox1_AfterUpdate()

Me.TextBox1.Text = Format(Me.TextBox1, “####,##”)

End Sub

2. Text Box Date Format –

To convert a value to a date format, double-click on the text box and select Text Behavior After Update. And apply the format code below.


Private Sub TextBox2_AfterUpdate ()

Me.TextBox2.Text = Format (Me.TextBox2, “dd / mm / yyyy”)

End Sub

Excel VBA Tutorial 5 - Text Box Properties, Text Box Currency Format and Date Format

You can use dashes or slashes in the date format or you can use a different format.

dd-mm-yyyy

dd/mmm/yyyy

mmm/dd/yyyy

Similarly, you can apply any format in the text box.

Me. TextBox .Text = Format (TextBox, “Format”)

0 / 0 / 0

Регистрация: 09.09.2014

Сообщений: 55

1

09.09.2015, 11:17. Показов 12932. Ответов 11


Студворк — интернет-сервис помощи студентам

Здравствуйте. TextBox отображает дату в формате 10/5/2015, а нужно 05.10.2015 Как изменить формат TextBox?



0



Апострофф

Заблокирован

09.09.2015, 11:55

2

Visual Basic
1
range.NumberFormatLocal="ДД.ММ.ГГГГ"

?



1



0 / 0 / 0

Регистрация: 09.09.2014

Сообщений: 55

10.09.2015, 19:35

 [ТС]

3

Не работает, или я не знаю — как это использовать.



0



Апострофф

Заблокирован

10.09.2015, 19:39

4

Как Вы вставляете дату в текстбокс?



0



kalbasiatka

414 / 262 / 82

Регистрация: 27.10.2012

Сообщений: 860

10.09.2015, 19:39

5

Visual Basic
1
Cells(1, 1) = Format(Textbox1, "dd.mm.yyyy")



0



SoftIce

es geht mir gut

11264 / 4746 / 1183

Регистрация: 27.07.2011

Сообщений: 11,437

10.09.2015, 20:21

6

kalbasiatka, не пойдет. Нужно менять местами месяц и число, а то формат их не различает.

Первое что придумалось:

Visual Basic
1
2
3
4
5
Dim s
    If UBound(Split(TextBox1.Text, "/")) = 2 Then
        s = Split(TextBox1.Text, "/")
        TextBox1.Text = CDate(s(1) & "." & s(0) & "." & s(2))
    End If



0



kalbasiatka

414 / 262 / 82

Регистрация: 27.10.2012

Сообщений: 860

10.09.2015, 22:41

7

Всё что надо он различает. Я так понимаю, что слеши появляются при загрузке в текстбокс. Поэтому дату перед загрузкой форматим.

Visual Basic
1
TextBox1 = Format(Cells(1, 1), "dd.mm.yyyy")

А чтобы была дата и в ячейке выгружаем преобразовав значение текстбокса

Visual Basic
1
Cells(1, 1) = CDate(TextBox1)



0



0 / 0 / 0

Регистрация: 09.09.2014

Сообщений: 55

11.09.2015, 08:50

 [ТС]

8

TextBox1 = Format(Cells(1, 1), «dd.mm.yyyy») На это выдает ошибку, выделяя «Format».

Добавлено через 8 минут
Не работает, выдаёт ошибку.



0



414 / 262 / 82

Регистрация: 27.10.2012

Сообщений: 860

11.09.2015, 11:24

9

Мне, как и многим другим помогающим, не дана сила телепатии. Что и как работает в вашем файле ни кто не знает, кроме вас.



0



0 / 0 / 0

Регистрация: 09.09.2014

Сообщений: 55

11.09.2015, 15:37

 [ТС]

10

Вот пример.

Вложения

Тип файла: rar LB.rar (18.7 Кб, 38 просмотров)



0



Апострофф

Заблокирован

11.09.2015, 16:38

11

Что Вы забили в свои тестбоксы, то там и показано…
В чём проблема — так и осталось загадкой.



0



414 / 262 / 82

Регистрация: 27.10.2012

Сообщений: 860

11.09.2015, 16:46

12

Лучший ответ Сообщение было отмечено llet45 как решение

Решение

Не заметил в файле моего кода, ну да ладно.



1



Разный формат даты в TextBox

Dмитрий

Дата: Воскресенье, 03.08.2014, 00:47 |
Сообщение № 1

Группа: Пользователи

Ранг: Участник

Сообщений: 91


Репутация:

9

±

Замечаний:
40% ±


Excel 2010

Здравствуйте!!! Подскажите, пожалуйста, почему дата отображается по-разному в TextBox на форме

К сообщению приложен файл:

4961427.xlsb
(16.6 Kb)

 

Ответить

Serge_007

Дата: Воскресенье, 03.08.2014, 07:05 |
Сообщение № 2

Группа: Админы

Ранг: Местный житель

Сообщений: 15894


Репутация:

2623

±

Замечаний:
±


Excel 2016

Здравствуйте
Так надо:
[vba]

Код

Private Sub UserForm_Initialize()
      Dim D1 As Date, D2 As Date
      D1 = [a1]: D2 = [b1]
      ‘TextBox1 = D1: TextBox2 = D2
      TextBox1 = Format(D1, «dd/mm/yyyy»): TextBox2 = Format(D2, «dd/mm/yyyy»)
End Sub

[/vba]Почему так — понятно?


ЮMoney:41001419691823 | WMR:126292472390

 

Ответить

Dмитрий

Дата: Вторник, 05.08.2014, 02:09 |
Сообщение № 3

Группа: Пользователи

Ранг: Участник

Сообщений: 91


Репутация:

9

±

Замечаний:
40% ±


Excel 2010

Прошу прощения. Остался без интернета на пару дней. Serge_007, спасибо за ответ. Получается, что невозможно изменить формат в уже заполненном TextBox. Или я чего-то не понял.

 

Ответить

wild_pig

Дата: Вторник, 05.08.2014, 08:51 |
Сообщение № 4

Группа: Проверенные

Ранг: Обитатель

Сообщений: 516


Репутация:

97

±

Замечаний:
0% ±


2003, 2013

Так вроде не тупит excel
[vba]

Код

TextBox1 = Format(Cells(1, 1), «dd/mm/yyyy»)
TextBox2 = Format(Cells(1, 2), «dd/mm/yyyy»)

[/vba]
Пардон, не глянул, что ответ Сергея должен был подойти.

Сообщение отредактировал wild_pigВторник, 05.08.2014, 08:54

 

Ответить

RAN

Дата: Вторник, 05.08.2014, 09:27 |
Сообщение № 5

Группа: Друзья

Ранг: Экселист

Сообщений: 5645


Именно. Для того, чтобы TextBox1 получил формат «dd/mm/yyyy», нужно выполнить макрос. Сам по себе макрос не запустится, его нужно запустить.
[vba]

Код

Private Sub UserForm_Initialize()
     Dim D1 As Date, D2 As Date
     D1 = [a1]: D2 = [b1]
     TextBox1 = D1: TextBox2 = D2
     TextBox1 = Format(TextBox1 , «dd/mm/yyyy»): TextBox2 = Format(TextBox2 , «dd/mm/yyyy»)
End Sub

[/vba]
Код выдает правильный результат, но только однократно, при загрузке формы.
Если вручную сменить значение в TextBox1, необходимо снова запустить форматирование.
[vba]

Код

Private Sub TextBox1_Exit()
      TextBox1 = Format(TextBox1 , «dd/mm/yyyy»)
End Sub

[/vba]


Быть или не быть, вот в чем загвоздка!

 

Ответить

Dмитрий

Дата: Вторник, 05.08.2014, 17:06 |
Сообщение № 6

Группа: Пользователи

Ранг: Участник

Сообщений: 91


Репутация:

9

±

Замечаний:
40% ±


Excel 2010

Сам по себе макрос не запустится, его нужно запустить.

Ну так мы его и запускаем
Private Sub UserForm_Activate()
1. Присваеваем TextBox1 = D1: TextBox2 = D2
2. Форматируем TextBox1 = Format(TextBox1, «dd/mm/yyyy»): TextBox2 = Format(TextBox2, «dd/mm/yyyy»)
3. Результат: TextBox1 — 08.05.2014; TextBox2 — 22.08.2014; вместо 05.08.2014 и 22.08.2014 соответственно
Речь не идет о дальнейшей смене каких то значений в TextBox. Я набросал всего лишь пример с форматированием однократно, при активации формы

 

Ответить

RAN

Дата: Вторник, 05.08.2014, 18:42 |
Сообщение № 7

Группа: Друзья

Ранг: Экселист

Сообщений: 5645

Понятно.
TextBox — это всегда текст.
[vba][/vba]
по умолчанию отображает дату в формате «mm/dd/yyyy»
Дальше этот текст преобразовывается текст в формате «dd/mm/yyyy».
А VBA, бедолага, не знает 08.05 это 8 мая или 5 августа. Но точно знает, что месяцев году всего 12 :D


Быть или не быть, вот в чем загвоздка!

 

Ответить

  • #1

Hi, all,

I have a userform with 5 input fields, four of which are textboxes (the other is a combobox). Two of the fields ask the user to input a date in the format dd/mm/yy, and one of them asks for a number.

Currently, these values are added to the worksheet as text values, even though the cells are formatted as dates/numbers. (Thus it also flags that the input data doesn’t correspond to the cell formatting).

I would like the dates to retain the day, month, and year data, but to only show dd/mm in the cell.
I would like the number to display as a number (allowing for decimals and zero).

Here’s the code that adds the form data to the worksheet:

VBA Code:

Private Sub Add_Eval_Add_Click()
Dim iCol As Long
Dim ws As Worksheet
Set ws = Worksheets("Gradebook")

'find first empty column in database
iCol = ws.Cells.Find(What:="*", SearchOrder:=xlColumns, _
    SearchDirection:=xlPrevious, LookIn:=xlValues).Column + 1

'check for an evaluation title
If Trim(Me.Eval_Title.Value) = "" Then
  Me.Eval_Title.SetFocus
  MsgBox "Please enter an evaluation title."
  Exit Sub
End If

'check for a category
If Trim(Me.Eval_Cat.Value) = "" Then
  Me.Eval_Cat.SetFocus
  MsgBox "Please choose a category."
  Exit Sub
End If

'check for an assigned date
If Trim(Me.Eval_Date.Value) = "" Then
  Me.Eval_Date.SetFocus
  MsgBox "Please enter the date the evaluation was assigned."
  Exit Sub
End If

'check for a due date
If Trim(Me.Eval_Due_Date.Value) = "" Then
  Me.Eval_Due_Date.SetFocus
  MsgBox "Please enter the due date."
  Exit Sub
End If

'check for a points value
If Trim(Me.Eval_Points.Value) = "" Then
  Me.Eval_Points.SetFocus
  MsgBox "Please enter the available points."
  Exit Sub
End If

'copy the data to the database
'use protect and unprotect lines,
'     with your password
'     if worksheet is protected
With ws
'  .Unprotect Password:="password"
  .Cells(1, iCol).Value = Me.Eval_Title.Value
  .Cells(2, iCol).Value = Me.Eval_Cat.Value
  .Cells(3, iCol).Value = Me.Eval_Date.Value
  .Cells(4, iCol).Value = Me.Eval_Due_Date.Value
  .Cells(5, iCol).Value = Me.Eval_Points.Value
'  .Protect Password:="password"
End With

'clear the data
Me.Eval_Title.Value = ""
Me.Eval_Cat.Value = ""
Me.Eval_Date.Value = ""
Me.Eval_Due_Date.Value = ""
Me.Eval_Points.Value = ""
Me.Eval_Title.SetFocus
End Sub

P.S. If you have any suggestions to optimise the code, I’m all ears!
P.P.S. Do I understand the code correctly that, if I have the worksheet protected, I can uncomment the lines

VBA Code:

.Unprotect Password:="password"

and

VBA Code:

.Protect Password:="password"

and replace «password» with the worksheet password?

Shade all formula cells

To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.

  • #2

hi ]tjdickinson,

In VBA textbox values (excluding numbers only) are considered as TEXT and when we populate cells with textbox values, they are transferred as text as well. Same goes for dates, thus formatting cells as Date does not have any effect. have a look at below examples:

VBA Code:

Sheets("sheet1").Range("a1") = TextBox1.Value                           'textbox value will be transferred as text
Sheets("sheet1").Range("a1").NumberFormat = "mmm/yyyy"                  'there will be no effect on cell value, since it is text

Sheets("sheet1").Range("a3") = Format(TextBox1.Value, "dd/mm/yyyy")     'textbox value will be transferred as text but formatted as date, the value will remain TEXT

Sheets("sheet1").Range("a2") = CDate(TextBox1.Value)                    'textbox value will be transferred as date
Sheets("sheet1").Range("a2").NumberFormat = "mmm/yyyy"                  'cell format will be changed to mmm and year, the value will remain DATE

Textbox1.value will place your value as text and as a result number format will not have any effect on such value.
format(textbox1.value, «mm/yyyy») will place your value as text but formatted in shape of month and year, but excel will read the cell value as text.
CDate(textbox1.value) will place your value as date and numberformat will change the date format, but the value will remain date.

1624709436543.png

hth…..

  • #3

hi ]tjdickinson,

In VBA textbox values (excluding numbers only) are considered as TEXT and when we populate cells with textbox values, they are transferred as text as well. Same goes for dates, thus formatting cells as Date does not have any effect. have a look at below examples:

VBA Code:

Sheets("sheet1").Range("a1") = TextBox1.Value                           'textbox value will be transferred as text
Sheets("sheet1").Range("a1").NumberFormat = "mmm/yyyy"                  'there will be no effect on cell value, since it is text

Sheets("sheet1").Range("a3") = Format(TextBox1.Value, "dd/mm/yyyy")     'textbox value will be transferred as text but formatted as date, the value will remain TEXT

Sheets("sheet1").Range("a2") = CDate(TextBox1.Value)                    'textbox value will be transferred as date
Sheets("sheet1").Range("a2").NumberFormat = "mmm/yyyy"                  'cell format will be changed to mmm and year, the value will remain DATE

Textbox1.value will place your value as text and as a result number format will not have any effect on such value.
format(textbox1.value, «mm/yyyy») will place your value as text but formatted in shape of month and year, but excel will read the cell value as text.
CDate(textbox1.value) will place your value as date and numberformat will change the date format, but the value will remain date.

View attachment 41652

hth…..

Hi, Fahad, thanks for your reply!

Okay, so I changed the code to include the CDate() function:

VBA Code:

  .Cells(3, iCol).Value = CDate(Me.Eval_Date.Value)
  .Cells(4, iCol).Value = CDate(Me.Eval_Due_Date.Value)

When I run the form and fill it in, I put (for example) 26/06 in the first date box and 27/06 in the second date box.

After I click ‘Add’, the cells receive the values
26/06/2021
27/06/2021
even though I didn’t put the year in the form. I would like the year not to display in order to minimise column width.

The Cell Number Format now says ‘Text’ instead of ‘Date’ (it was set to ‘Date’ with custom formatting dd/mm before I added the data). However, the flag in the corner of the cell has gone away, which had been indicating that the cell contents didn’t fit the intended format. So I’m not quite sure what’s going on there.

I don’t quite understand how to use the NumberFormat parameter. I can’t call a specific cell, because each instance of the userform adds a new column of data (so the reference is constantly changing). Is there something similar to CDate() for numbers?

  • #4

hi ]tjdickinson,

In VBA textbox values (excluding numbers only) are considered as TEXT and when we populate cells with textbox values, they are transferred as text as well. Same goes for dates, thus formatting cells as Date does not have any effect. have a look at below examples:

VBA Code:

Sheets("sheet1").Range("a1") = TextBox1.Value                           'textbox value will be transferred as text
Sheets("sheet1").Range("a1").NumberFormat = "mmm/yyyy"                  'there will be no effect on cell value, since it is text

Sheets("sheet1").Range("a3") = Format(TextBox1.Value, "dd/mm/yyyy")     'textbox value will be transferred as text but formatted as date, the value will remain TEXT

Sheets("sheet1").Range("a2") = CDate(TextBox1.Value)                    'textbox value will be transferred as date
Sheets("sheet1").Range("a2").NumberFormat = "mmm/yyyy"                  'cell format will be changed to mmm and year, the value will remain DATE

Textbox1.value will place your value as text and as a result number format will not have any effect on such value.
format(textbox1.value, «mm/yyyy») will place your value as text but formatted in shape of month and year, but excel will read the cell value as text.
CDate(textbox1.value) will place your value as date and numberformat will change the date format, but the value will remain date.

View attachment 41652

hth…..

Update:

Guided and informed by your suggestions, I found a near solution, but there’s still one glitch:

I added an Exit event to each textbox setting the format of the textbox contents

VBA Code:

Private Sub Eval_Date_Exit(ByVal Cancel As MSForms.ReturnBoolean)

Eval_Date.Text = Format$(Eval_Date.Text, "dd/mm")

End Sub

and

VBA Code:

Private Sub Eval_Points_Exit(ByVal Cancel As MSForms.ReturnBoolean)

Eval_Points.Text = Format$(Eval_Points.Text, "##0.0")

End Sub

Then, in the Click event adding the data to the worksheet, I added the .NumberFormat function after each value is added to the worksheet:

VBA Code:

With ws
'  .Unprotect Password:="password"
  .Cells(1, iCol).Value = Me.Eval_Title.Value
  .Cells(2, iCol).Value = Me.Eval_Cat.Value
  .Cells(3, iCol).Value = Me.Eval_Date.Value
  .Cells(3, iCol).NumberFormat = "dd/mm"
  .Cells(4, iCol).Value = Me.Eval_Due_Date.Value
  .Cells(4, iCol).NumberFormat = "dd/mm"
  .Cells(5, iCol).Value = Me.Eval_Points.Value
  .Cells(5, iCol).NumberFormat = "##0.0"
'  .Protect Password:="password"
End With

Now the dates show up correctly in the sheet.

The number (Eval_Points) displays correctly, and the number format in the worksheet shows ‘Custom’ (rather than ‘Text’), which is good, but I still get a flag that says ‘Number stored as text’.

1624729770862.png

  • #5

this will disable the error, but it works across the whole workbook

VBA Code:

Application.ErrorCheckingOptions.NumberAsText = False

  • #6

this will disable the error, but it works across the whole workbook

VBA Code:

Application.ErrorCheckingOptions.NumberAsText = False

Thanks, diddi! My only concern is whether calling these values in other functions will result in errors, if the values are stored here as text.

Is it possible to apply your code only to the current worksheet (and not the whole workbook)?
If I use this code, where do I put it? In the ‘ThisWorkbook’ object? or in the current sheet object?

  • #7

use the Val( ) function in VBA code
errorcheckingoptions is an application level value, so it cannot be applied to individual sheets or ranges. sorry

you would be best to place it in WorkBook_Open sub. dont forget to set to true again before exiting the workbook

  • #8

Or try the following

VBA Code:

.Cells(5, iCol).Value = Me.Eval_Points.Value
  .Cells(5, iCol).NumberFormat = "General"

hth….

Wookiee

Like this post? Please share to your friends:
  • Vba excel textbox только числа
  • Vba excel textbox проверка
  • Vba excel textbox добавить
  • Vba excel textbox денежный формат
  • Vba excel textbox в ячейку