Compile error invalid character

This is a weird problem with the VBE 6.5 in Office 2011, running natively on a Mac.

This is a weird problem with the VBE 6.5 in Office 2011, running natively on a Mac.

Sometimes, yet often, when I select a word by double clicking on it or a line by highlighting that line in the editor and then copy/paste it somewhere else in the code, the compiler throws the error «Compile error: Invalid character»

The thing is, what I see has been pasted is exactly the same as the source text. However, if I then paste the same clipboard item to a text editor, I can see that there is an ‘invisible’ character at the end of the string which is counted in the text editor
where the cursor is shifted past it but does not shown on the screen!!!

Back in the VBE, if I select a line that is dubious and drag it, the semi transparent dragged text has a ‘>’ character on a new line.

In some copy/paste cases, the compiler doesn’t see an error but the code doesn’t work as expected and I have spent hours debugging stuff that has invisible characters in it (the hardest debugging I’ve ever had to do!).

I’m not sure if this example will paste correctly into the forum but this looks like 19 characters but is in fact 20 as there is the offending copy/paste invisible character between ‘Test’ and ‘.’

<code>Test.Value = False</code>

This seems to be a major oversight in the code of the VBE 6.5 so are Microsoft aware of this and when is it due to be fixed?


Jamie.

I got a VB SCRIPT off the internet to create new mail alerts for secondary email accounts in Outlook(2010).

Now this is the first part of the code, and when running Outlook, it gives me the following error:

«Compile Error: Invalid Character»

The debugger underlines the _ character in the following line: «sndPlaySoundA» _

'On the next line change the file name and path of the sound you want to play.'
Public Const SOUND_TO_PLAY = "C:WindowsMediaSpeech On.wav"
Public Const SND_ASYNC = &H1

Public Declare Function sndPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" _ 
(ByVal lpszSoundName As String, ByVal uFlags As Long) As Long Public Declare Function    MessageBox _
    Lib "User32" Alias "MessageBoxA" _
        (ByVal hWnd As Long, _
        ByVal lpText As String, _
        ByVal lpCaption As String, _
        ByVal wType As Long) _
    As Long


Function OpenOutlookFolder(strFolderPath As String) As Outlook.MAPIFolder
    ' Purpose: Opens an Outlook folder from a folder path.'
    ' Written: 4/24/2009'
    ' Author:  BlueDevilFan'
    ' Outlook: All versions'
    Dim arrFolders As Variant, _
        varFolder As Variant, _
        bolBeyondRoot As Boolean
    On Error Resume Next
    If strFolderPath = "" Then
        Set OpenOutlookFolder = Nothing
    Else
        Do While Left(strFolderPath, 1) = ""
            strFolderPath = Right(strFolderPath, Len(strFolderPath) - 1)
        Loop
        arrFolders = Split(strFolderPath, "")
        For Each varFolder In arrFolders
            Select Case bolBeyondRoot
                Case False
                    Set OpenOutlookFolder = Outlook.Session.Folders(varFolder)
                    bolBeyondRoot = True
                Case True
                    Set OpenOutlookFolder = OpenOutlookFolder.Folders(varFolder)
            End Select
            If Err.Number <> 0 Then
                Set OpenOutlookFolder = Nothing
                Exit For
            End If
        Next
    End If
    On Error GoTo 0
End Function

UPDATE: A new error has risen: (After I fixed the New line issue on line 1 after «sndPlaySoundA») as refered to by Adrian below)

«Compile Error Expected: End of statement» and the following word is highlighted: «Public»

UPDATE2: Next error:

Compile Error: User defined type not defined(For «Mailbox — supportdeskInbox»)

Dim objFM1 As FolderMonitor

Private Sub Application_Quit()
    Set objFM1 = Nothing
End Sub

Private Sub Application_Startup()
    Set objFM1 = New FolderMonitor
    'Edit the folder path on the next line as needed.'
    objFM1.FolderToWatch OpenOutlookFolder("Mailbox - supportdeskInbox")
    End Sub

  • #1

Hello,

Trying to write some macros, the first one clears a range when clicking a button.
The other one is supposed to scan a cel range for parsing purposes.

I’m stuck on both, getting «Compile Error: Invalid Character» and don’t understand why. I highlighted the problematic rows below in red.
Any assistance would be greatly appreciated.

———————————————————————————————
Sub Clear_NOTAM()
Dim NOTAMSheet As Worksheet
Dim LastNOTAMRow As Integer

Set NOTAMSheet = Worksheets(«Copy Paste NOTAM»)
LastNOTAMRow = NOTAMSheet.UsedRange.Rows(NOTAMSheet.UsedRange.Rows.Count).Row

Worksheets(«Copy Paste NOTAM»).Range(«A1:B» & str(LastNOTAMRow)).Value = «»

End Sub
———————————————————————————————
Sub Reformat_NOTAM()
Dim NOTAMSheet As Worksheet
Dim LastNOTAMRow As Integer
Dim NOTAMInputRange As Range
Dim RowIdx As Integer
Dim ColIdx As Integer
Dim CellValue As String

Set NOTAMSheet = Worksheets(«Copy Paste NOTAM»)
LastNOTAMRow = NOTAMSheet.UsedRange.Rows(NOTAMSheet.UsedRange.Rows.Count).Row ‘Find last row

for RowIdx = 1 to LastNOTAMRow

End Sub

Add Bullets to Range

Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)

  • #2

step thru your code and check the value of LastNOTAMRow
if it is empty or 0 that is your problem

  • #3

Your code has an extra character in each of your highlighted lines which doesn’t show up when copied and pasted here.

The first line
Worksheets(«Copy Paste NOTAM»).Range(«A1:B» & str(LastNOTAMRowhere)).Value = «»

The second line
for RowIdx = 1 to LastNOTAMRowhere

Copy and paste those lines into a cell as text and then run this code, you’ll see.

Code:

Sub CheckOfCharacters()
    Dim i As Integer
    Dim str As String

str = ActiveCell.Value

For i = 1 To Len(str)
    Debug.Print Mid(str, i, 1) & "  =  " & Asc(Mid(str, i, 1))
Next

End Sub

  • #4

Thanks NoSparks. I was going nuts with this one!

It’ very odd. Why wouldn’t it show up? And where would it come from?

Thank you!

Last edited: Jul 31, 2015

MARK858

Fluff

  • Remove From My Forums
  • Question

  • Dear Script-Guys,

    i found a script for a message box for Password Expires after login under Windows 7…but i become an error on Line 1 Char 1, Error: Invalid character, Code: 800A0408, Source: Microsoft VBSCript compilation error…here is the script:

    Dim oDomain
    Dim oUser
    Dim maxPwdAge
    Dim numDays
    Dim warningDays

    warningDays = 29

    Set LoginInfo = CreateObject(«ADSystemInfo») 
    Set objUser = GetObject(«LDAP://» & LoginInfo.UserName & «») 

    strDomainDN = UCase(LoginInfo.DomainDNSName)
    strUserDN = LoginInfo.UserName

    Set oDomain = GetObject(«LDAP://» & strDomainDN)
    Set maxPwdAge = oDomain.Get(«maxPwdAge»)

    ‘========================================
    ‘ Calculate the number of days that are
    ‘ held in this value.
    ‘========================================
    numDays = CCur((maxPwdAge.HighPart * 2 ^ 32) + _
                    maxPwdAge.LowPart) / CCur(-864000000000)
    ‘WScript.Echo «Maximum Password Age: » & numDays

    ‘========================================
    ‘ Determine the last time that the user
    ‘ changed his or her password.
    ‘========================================
    Set oUser = GetObject(«LDAP://» & strUserDN)

    ‘========================================
    ‘ Add the number of days to the last time
    ‘ the password was set.
    ‘========================================
    whenPasswordExpires = DateAdd(«d», numDays, oUser.PasswordLastChanged)
    fromDate = Date
    daysLeft = DateDiff(«d»,fromDate,whenPasswordExpires)

    ‘WScript.Echo «Password Last Changed: » & oUser.PasswordLastChanged

    if (daysLeft < warningDays) and (daysLeft > -1) then
        Msgbox «Password Expires in » & daysLeft & » day(s)» & » at » & whenPasswordExpires & chr(13) & chr(13) & «Once logged in, press CTRL-ALT-DEL and» & chr(13) & «select the ‘Change a password’ option»,
    0, «PASSWORD EXPIRATION WARNING!»

    End if

    ‘========================================
    ‘ Clean up.
    ‘========================================
    Set oUser = Nothing
    Set maxPwdAge = Nothing
    Set oDomain = Nothing

    Can anybody help me for understanding this script and solve the problem?

    thx for helping

    Richard

Answers

  • File is saved as Unicode.  Save as ANSI.

    A Unicode file has two bytes in the beginning.  The first one is likely a null (0) and the second the numerical code for the character set index.  The null will cause that error.

    Here is the error I get when saving a VBS as a Unicode Big-Endian:

    E:test2utest.vbs(1, 1) Microsoft VBScript compilation error: Invalid character

    Little indians and ANSI will not cause this error.  Unicode big-endian and UTF-8 will.

    The trigger for Unicode is the first four bytes:

    ANSI — no 4 char code
    UTF-8 EF BB BF 27
    Unicode-big FE FF 00 27
    Unicode-little FF FE 27 00

    Note that the byte order for big/little is exactly swapped and the codes are identical.

    The first 2 bytes as posted are the flag for the encoding and the second two bytes for the character set.

    This can happen when moving between 32 and 64 bit environments.  The file encoding is limited in WSH.

    The FF FE in the above will actually be the first character of the file when opened as an ANSI file.

    All four characters are illegal in ANSI VBScript.  WSH will sitch to Unicode if the first two bytes are FF FE. Except for this exception. All lines in VBScript MUST begin with a printable character.

    ANSI mode does not know about encoding flags.  Only Unicode knows how to read the first 4 bytes of the file.

    ANSI is not portable due to byte order.  Unicode is portable because the first four bytes signal the byte order. 


    ¯_(ツ)_/¯

    • Proposed as answer by

      Friday, September 28, 2012 12:58 PM

    • Marked as answer by
      jurkovri
      Tuesday, October 2, 2012 9:32 AM
    • Edited by
      jrv
      Tuesday, October 2, 2012 1:06 PM
      Altrered descritpon slightly so as to be almost accurate.

Running a VBS script resulted in error Microsoft VBScript compilation error: Invalid character

image

The line of code apparently containing invalid character was:

    Const ForWriting = 2

Opening in a Hex Editor it was revealed the “spaces” before the word const were something else

image

Selecting the blank spaces, copying them, pasting into a notepad search/replace didn’t remove them.

Using HexEdit I search/replaced the relevant bytes with 09 (tab)

image

After this some instances of C2 or A0 were on their own still causing the error, these I replaced with 0x20 (space)

image

After this the script ran fine…

About chentiangemalc

specializes in end-user computing technologies. disclaimer 1) use at your own risk. test any solution in your environment. if you do not understand the impact/consequences of what you’re doing please stop, and ask advice from somebody who does. 2) views are my own at the time of posting and do not necessarily represent my current view or the view of my employer and family members/relatives. 3) over the years Microsoft/Citrix/VMWare have given me a few free shirts, pens, paper notebooks/etc. despite these gifts i will try to remain unbiased.

This entry was posted in Uncategorized. Bookmark the permalink.

  1. 03-02-2013, 11:29 AM


    #1

    dogguy2010 is offline


    Registered User


    compile error: invalid character — seems to be on the dollar sign

    When using …. FIND(» — $ «,A1) … within a macro, I get a compile error: invalid character and it highlights the $. Ultimately, I need the LEFT(A1,FIND(» — $ «,A1)).
    How can I find that string using a macro?


  2. 03-02-2013, 11:33 AM


    #2

    Re: compile error: invalid character — seems to be on the dollar sign

    Find is a worksheet function and not a VBA function. Are you using it in a formula line? What does your entire code look like? That would be helpful. You may have to wrap the quotes in an additional set of quotes, but won’t know for sure until we see all the code.

    Alan


  3. 03-02-2013, 11:34 AM


    #3

    Re: compile error: invalid character — seems to be on the dollar sign

    Is that part of a formula?

    If it is you need to double up the quotes.

    Can you post the rest of the code?

    If posting code please use code tags, see here.


  4. 03-02-2013, 11:47 AM


    #4

    dogguy2010 is offline


    Registered User


    Re: compile error: invalid character — seems to be on the dollar sign

    Here is the formula =CONCATENATE(«$»,RIGHT(A1,LEN(A1)-(FIND(» — $ «,A1)+4)))

    This is the contents of A1: Anchor Communcations — Saint Charles — $ 15.00

    Here is my code in the macro:
    Range(«J1») = «=CONCATENATE(«$»,RIGHT(A1,LEN(A1)-(FIND(» — $ «,A1)+4)))»: Range(«J1»).Copy
    Range(«J1:J» & Range(«A» & Rows.Count).End(xlUp).Row).Select
    ActiveSheet.Paste:

    Results of J1 should be $15


  5. 03-02-2013, 12:10 PM


    #5

    Like I said you need to double up the quotes.


  6. 03-02-2013, 12:14 PM


    #6

    Re: compile error: invalid character — seems to be on the dollar sign

    Entia non sunt multiplicanda sine necessitate


Знатоки помогите некому обратиться кроме вас мне дали код по ассемблеру сказали ошибок нет но на стадии трансляции и тд выдает ошибку не пойму почему и как её решить потому что на этом этапе я дальше не смогу решить остальные задания
сам код :

Assembler
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
TITLE EX_PROG
PAGE ,123
STACK SEGMENT PARA STACK 'STACK'
DB 64 DUP ('STACK')
STACK ENDS
DSEG SEGMENT PARA PUBLIC 'DATA'
SOURCE DB 10,20,30,40
DEST DB 4 DUP(?)
DSEG ENDS
SUBTTL 
PAGE 
CSEG SEGMENT PARA PUBLIC 'CODE'
ASSUME CS:CSEG, DS:DSEG, SS:STACK
OUR_PROG PROC FAR
PUSH DS
SUB AX,AX
PUSH AX
MOV AX,DSEG
MOV DS,AX
MOV DEST,0
MOV DEST+1,0
MOV DEST+2,0
MOV DEST+3,0
MOV AL, SOURCE
MOV DEST+3,AL
MOV AL, SOURCE+1
MOV DEST+2,AL
MOV AL, SOURCE+2
MOV DEST+1,AL
MOV AL, SOURCE+3
MOV DEST,AL
RET
OUR_PROG ENDP
CSEG ENDS
END OUR_PROG

Сами задания:
1. Набрать приведенную в тексте программу на ассемблере с использованием
редактора текста.
2. Оттранслировать программу в объектный код.
3. Скомпоновать программу (получить исполнимый файл). Изучить листинг
программы.
4. Провести отладку программы и проверить получаемые результаты.
5. Внести в программу следующие изменения: задать исходную таблицу
SOURCE из 5 двухбайтовых шестнадцатеричных переменных и скопировать эту
новую таблицу в DEST.
6. В сегменте данных определить переменные, заполнив их следующими
значениями:

− 5 байтов A, B, C, D, E;
− 5 двухбайтовых слов AA, BB, CC, DD, EE;
− 5 двойных слов AAAA, BBBB, CCCC, DDDD, EEEE;
7. Получить исполнимый файл программы с данными пункта 6 и изучить дамп
памяти данных с целью уяснения механизма выравнивания.



0



Понравилась статья? Поделить с друзьями:
  • Compile error in hidden module this error commonly occurs when code is
  • Compile error in hidden module solvercode excel 2016 как исправить
  • Compile error in hidden module module1
  • Compile error in hidden module ipsolve55
  • Compile error in hidden module excel 2010 как исправить