1

Excel VBA, I'm having a problem with an excel macro with function

` StrComp(FileLine, "*/")`

The purpose of the code is to find duplicates in an .h file.

And I want to exclude all commented declarations, so I've added this piece of code:

VarIsAComment = StrComp(FileLine, "//#define", vbTextCompare)

and it's working fine, but the problem starts when I try to find comment with "/*".. I've tryied this code:

While Not EOF(1)
            Line Input #1, FileLine
            CurLineNum = CurLineNum + 1
            If (StrComp(FileLine, "#define", vbBinaryCompare)) Then
            
                VarIsAComment = StrComp(FileLine, "//#define", vbTextCompare) //Woks fine
                If (StrComp(FileLine, "/*")) Then CommentStarted = 1 //not working
                If (StrComp(FileLine, "*/")) Then CommentStarted = 0 

So the problem is that if FileLine is something like this:

#define mBlk    bytem[12]/*comment*/ 

it works fine, but when FileLine is only /* CommentStarted stays to false and then goes to true only on the next line and then returns to false in the same cycle.

Any idea?

Thanks

Edo
  • 11
  • 1
  • Have you researched how `StrComp` works? It will return a zero (`0`) when the two strings match, not a `True`. Also, asterisks (`*`) are treated as wildcards. – CLR May 25 '23 at 07:43
  • I guess you misunderstood `StrComp`. It will check if two strings are *identical*. If yes, it returns 0, else it returns either -1 or +1 (depending on which string is "smaller"). See https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/strcomp-function and also https://stackoverflow.com/questions/45215786/best-way-to-compare-strings-in-vba/45216693#45216693. You are probably looking for `InStr` – FunThomas May 25 '23 at 07:44

1 Answers1

1

As written in the comments, you seem to misunderstand how StrComp works. Your statement StrComp(FileLine, "#define", vbBinaryCompare will always return either 1 or -1, except if the line is exactly "#define". Both values 1 and -1 are interpreted as True (in VBA, as in most languages, 0 is converted to False and every other value is converted to True).

Similarly, VarIsAComment = StrComp(FileLine, "//#define", vbTextCompare) will always be True except if the line is exactly "//#define".

What you want is to check

o If line starts with #define:

If FileLine like "#define*" Then

o If line contains #define:

If InStr(FileLine, "#define") > 0 Then

o Get rid of the // comment:

Dim p  As Long
p = InStr(FileLine, "//")
If p > 0 Then 
   If p > 1 Then FileLine = Left(FileLine, p-1) Else FileLine = ""
End If

o Get rid of /* comments and check if we start (or end) a comment block

Dim p1 As Long, p2  As Long
p1 = InStr(FileLine, "/*")
p2 = InStr(FileLine, "*/")
If p1 > 0 Then 
    If p1 > 1 Then FileLine = Left(FileLine, p1-1) Else FileLine = ""
    CommentStarted = True
End If
If p2 > p1 Then CommentStarted = False
FunThomas
  • 23,043
  • 3
  • 18
  • 34