Меню

Expression expected ошибка vba

I am working on some homework and I can’t figure out why my code won’t work. The assignment is to request a name then respond in red text in B10.

Here is my code:

enter image description here

Any help would be great- Thanks!

Community's user avatar

asked Apr 7, 2014 at 1:21

user3504930's user avatar

2

This error comes from the line With RAnge("b10").Font.ColocarIndex = 3, With supose to be used only to objects (not expressions)

sName = Application.InputBox(Prompt:="Please enter your name.", Type:=2)    
With Sheets("MyNewSheet").Range("B10")
    .Font.ColorIndex = 3
    .Value = sName 
End With

answered Apr 7, 2014 at 2:18

Roger Barreto's user avatar

Roger BarretoRoger Barreto

1,9541 gold badge16 silver badges21 bronze badges

Consider:

Sub qwerty()
    Sheets("MyNewSheet").Activate
    With Range("B10")
        .Font.ColorIndex = 3
        strName = Application.InputBox(Prompt:="Please enter your name.", Type:=2)
        .Value = strName
    End With
End Sub

answered Apr 7, 2014 at 2:09

Gary's Student's user avatar

Gary’s StudentGary’s Student

94.9k9 gold badges58 silver badges97 bronze badges

Microsoft Dynamics GPI realise that the use of VBA in modifications and customisations is something that needs to be carefully considered with Microsoft Dynamics GP 2013 including a Silverlight based Web Client which cannot use VBA. I had a requirement from a client for a modification to the Debtor Enquiry (Customer Inquiry to the Americans reading) to include the sum of the displayed transactions on the window and as this was a small client with GP installed locally on each PC there is no requirement for the web client, I felt able to perform this change using Modifier using some VBA.

I added the required fields to the VBA project but encountered an error message when writing the VBA code to concatenate the fields into the SQL statement I was going to use to get the data;

Microsoft Visual Basic: Compile error: Expected: expressionMicrosoft Visual Basic: Compile error: Expected: expression

It took me a few minutes to realise that the cause of the error is that To is a restricted keyword in VBA. Once I had realised this, I was able to quickly work around the error by updating the code to refer to the field To with more accuracy;

Microsoft Visual Basic

The red ringed text shows how I got VBA to accept the variable. The Me refers to the Debtor Enquiry window and specifies that To is not a keyword but a child object of the window.

  • Remove From My Forums
  • Question

  • Hello Folks

    I am a newbee when it comes to writing lines in a programming language.

    I was given a task of writing a condition for a project.

    I was using the «OR» operator and it gives me an Expression Expected Error. Amusingly, the error is in different versions of Visual Basic Express Edition.

    In 2008, there is no error. But in VB 2005, i get the Expression Expected Error, Was wondering if it was the version or my own fault in writing. Please advise.

    If

    mventry(«something»).IsPresent
    AndAlso mventry(«something»).StringValue.ToLower
    =
    «something»
    Or
    If(mventry(«something»).Values.Contains(«something»))

    Then

Answers

  • Judging by the code you have an extra If — but the code layout is poor and there might be some missing.

    I’ve found the best way to post code is to copy and paste it into Notepad, then copy and paste from Notepad — the code button here often seems to mess up code copied directly from VB.


    Regards David R
    —————————————————————
    Every program eventually becomes rococo, and then rubble. — Alan Perlis
    The only valid measurement of code quality: WTFs/minute.

    • Proposed as answer by

      Tuesday, April 19, 2011 5:47 AM

    • Marked as answer by
      Mike FengModerator
      Wednesday, April 27, 2011 9:29 AM

  • I agree — you probably should just drop the second «If» — you don’t need it with «Or» expressions.  Also, consider using the OrElse operator — it is a short-circuiting logical operator just like the AndAlso you are using that will only evaulate
    the second condition if the first one is False.  There are few ordinary cases where an Or is preferred to an OrElse.  Here’s what your line would look like this way (assuming we’ve interpreted it correctly):

    If (mventry("something").IsPresent AndAlso mventry("something").StringValue.ToLower = "something") OrElse (mventry("something").Values.Contains("something")) Then

    • Proposed as answer by
      Mike FengModerator
      Tuesday, April 19, 2011 5:47 AM
    • Marked as answer by
      Mike FengModerator
      Wednesday, April 27, 2011 9:29 AM

  • 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.

  • #1

Hi, I keep getting the error messgae «compile error: expected expression»
VBA also highlights :=

Sub Solve()
SolverOk.SetCell:= «$I$15″, MaxMinVal:=1, ValueOf:=»0″, ByChange:=»$I$3:$I$12»
SolverSolve UserFinish:=True
End Sub

Any ideas? Thanks in advance. 😀

Enter current date or time

Ctrl+: enters current time. Ctrl+; enters current date. Use Ctrl+: Ctrl+; Enter for current date & time.

shg

shg

MrExcel MVP


  • #2

Welcome to the board.

Replace the dot after SolverOK with a space.

  • #3

Oh it worked. Thanks a lot. 😀

shg

shg

MrExcel MVP


  • #4

You’re welcome, good luck.

6StringJazzer

Threads
1,186,141
Messages
5,956,143
Members
438,235
Latest member
robbfisher83

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • Expression expected error

  1. Jun 14th, 2017, 04:53 AM


    #1

    curiousman is offline

    Thread Starter


    Junior Member


    Expression expected error

    Hi,

    I have a source code giving «expression expected» error. A small piece of this code below and whole source code is at the attachment. How can I fix this error? Thanks everybody.

    ————————-
    Private Sub ConnectToSQL()

    Dim con As New SqlConnection
    Dim cmd As New SqlCommand
    Dim Password As String
    Dim Password2 As String
    Dim userName As String

    Try
    If (EXPRESSION EXPECTED)
    ‘change the data source and initial catalog according to your sql server engine and data base
    con.ConnectionString = «Data Source = Localhost; Initial Catalog = hdur750; Integrated Security = True»

    ——————————————


  2. Jun 14th, 2017, 06:42 AM


    #2

    Re: Expression expected error

    An If statement needs an expression that evaluates to true or false an If without any condition is meaningless.

    Could you post the relevant section of code here please, show the If statement in full if you have to — most people (myself included) would rather not download a word document from an unknown source just to read some source code.


  3. Jun 14th, 2017, 07:49 AM


    #3

    curiousman is offline

    Thread Starter


    Junior Member


    Re: Expression expected error

    Thank you for your answer. Here is the code. This is a login code in Visual Basic and SQL database

    Code:

    Imports System.Data
    Imports System.Data.SqlClient
    Public Class giris
    
        Private Sub giris_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    
        End Sub
    
        'Login Button
        Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnLogin.Click
    
            ConnectToSQL()
    
        End Sub
    
        'Connect to SQL method
    
        Private Sub ConnectToSQL()
    
            Dim con As New SqlConnection
            Dim cmd As New SqlCommand
            Dim Password As String
            Dim Password2 As String
            Dim userName As String
    
            Try
                If        (EXPRESSION EXPECTED)
                        'change the data source and initial catalog according to your sql server engine and data base
                    con.ConnectionString = "Data Source = Localhost; Initial Catalog = hdur750; Integrated Security = True"
                    con.Open()
    
                    cmd.Connection = con
                    'change the data fields names and table according to your database
                    cmd.CommandText = " SELECT  userid, Password FROM   login WHERE   (userid = '" & txtKullanici.Text & "' ) AND (Password = '" & txtSifre.Text & "')"
    
                    Dim lrd As SqlDataReader = cmd.ExecuteReader()
                    If lrd.HasRows Then
                        While lrd.Read()
    
                            'Do something here
                            Password = lrd("password").ToString()
                            userName = lrd("userid").ToString()
    
                            Password2 = txtKullanici.Text()
    
                            If Password = Password2 And userName = txtKullanici.Text Then
    
                                MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
                                            )
                                anasayfa.Show()
                                Me.Hide()
    
                                'Clear all fields
                                txtKullanici.Text = ""
                                txtSifre.Text = ""
    
                            End If
    
                        End While
    
                    Else
                        MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                        'Clear all fields
                        txtSifre.Text = ""
                        txtKullanici.Text = ""
                    End If
    
                End If
    
            Catch ex As Exception
                MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
    
            Finally
                con.Close() 'Whether there is error or not. Close the connection.
    
            End Try
    
        End Sub
    
        Private Sub txtKullanici_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtKullanici.TextChanged
    
        End Sub
    
        Private Sub txtSifre_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtSifre.TextChanged
    
        End Sub
    
        Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
            'User clicking on cancel button only clears field
            ' and refocus to first field
    
            txtKullanici.Text = ""
            txtSifre.Text = ""
            txtKullanici.Focus()
        End Sub
    
    End Class


  4. Jun 14th, 2017, 08:13 AM


    #4

    Re: Expression expected error

    An If statement is used to make a decision about what code to execute based on checking a condition, if the condition is true then you execute the code, if the condition is false then you would execute the code in the «else» part (if one exists).

    You need to decide what you are trying to do here, under what conditions should you be running the code that follows the If statement? Once you have decided on this bit then writing the code to check if it is met should be easy.

    If there is no decision to make then you don’t need an If statement.

    You have a working example of an If further down in the code you posted «If lrd.HasRows Then» and again with «If Password = Password2 And userName = txtKullanici.Text Then»


  5. Jun 14th, 2017, 08:58 AM


    #5

    curiousman is offline

    Thread Starter


    Junior Member


    Re: Expression expected error

    I copied this code from Internet and changed the name of TextBox, Label, Button, Database ..etc. according to my Project.
    In original source code there is not any expression after «If» where the mistake happens. So I couldn’t find any solution here.

    Thanks for your interest a lot.


  6. Jun 14th, 2017, 09:05 AM


    #6

    Re: Expression expected error

    If there is nothing needed then just delete the If and the matching End If and you should be fine.


  7. Jun 14th, 2017, 09:09 AM


    #7

    Re: Expression expected error

    As you don’t know what it would be used for, it would be best to remove that «If» line, and the matching «End If» (just before the Catch).

    edit: I was too slow!


  8. Jun 16th, 2017, 07:00 AM


    #8

    Re: Expression expected error

    Hi…
    Well the first use of a IF in there i can think of is to check if the Textbox’s controls are empty or not, so here is a sample code:

    Code:

    Private Sub ConnectToSQL()
    
            Dim con As New SqlConnection
            Dim cmd As New SqlCommand
            Dim Password As String
            Dim Password2 As String
            Dim userName As String
    
            Try
                If txtKullanici.Text <> "" And txtSifre.text <> "" Then
    
                    'change the data source and initial catalog according to your sql server engine and data base
                    con.ConnectionString = "Data Source = Localhost; Initial Catalog = hdur750; Integrated Security = True"
                    con.Open()
    
                    cmd.Connection = con
                    'change the data fields names and table according to your database
                    cmd.CommandText = " SELECT  userid, Password FROM   login WHERE   (userid = '" & txtKullanici.Text & "' ) AND (Password = '" & txtSifre.Text & "')"
    
                    Dim lrd As SqlDataReader = cmd.ExecuteReader()
                    If lrd.HasRows Then
                        While lrd.Read()
    
                            'Do something here
                            Password = lrd("password").ToString()
                            userName = lrd("userid").ToString()
    
                            Password2 = txtKullanici.Text()
    
                            If Password = Password2 And userName = txtKullanici.Text Then
    
                                MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
                                            )
                                anasayfa.Show()
                                Me.Hide()
    
                                'Clear all fields
                                txtKullanici.Text = ""
                                txtSifre.Text = ""
    
                            End If
    
                        End While
    
                    Else
                        MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                        'Clear all fields
                        txtSifre.Text = ""
                        txtKullanici.Text = ""
                    End If
    
                End If
    
            Catch ex As Exception
                MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
    
            Finally
                con.Close() 'Whether there is error or not. Close the connection.
    
            End Try
    
        End Sub

    But as refered in the upper coments, if you using a «IF» clause its to validate a condition TRUE, FALSE, EQUAL, Superior, Inferior, Diferent, etc…. so when you looking for help especify what do you want to do.

    https://docs.microsoft.com/en-us/dot…else-statement

    PS: You can also be wanting to check if the database exists, if SQL server is there, explain what you want to do maybe people will be able to help.

    Last edited by Mike Storm; Jun 16th, 2017 at 07:09 AM.


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • Expression expected error

Tags for this Thread


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Explorer exe произошла ошибка
  • Explorer exe ошибка что значит