Vbscript how to find the first char from the end in text - vbscript

I have problem with find the first char from the end in text.
For example, find space(" ") or new line(vbCrLf) on "Father go home" i get the index of first space from the end and on "Father go home/ntomorrow" i get the index of /n.
my code:
Function checkTextFunction( i_valueCheck)
Dim whereSpace
Dim WhereNewLine
Dim indexOFirstSpaceFromTheEnd
If Right(i_valueCheck,1) = " " Or Right(i_valueCheck,1) = vbCrLf Then
indexOFirstSpaceFromTheEnd = -1
Else
whereSpace = InStrRev(i_valueCheck, " ", -1,0)
WhereNewLine = InStrRev(i_valueCheck, vbCrLf, -1,0)
If whereSpace < WhereNewLine Then
indexOFirstSpaceFromTheEnd = whereSpace
Else
indexOFirstSpaceFromTheEnd = WhereNewLine
End If
End IF
WriteLogFileLine "indexOFirstSpaceFromTheEnd: " & indexOFirstSpaceFromTheEnd & " Right(i_valueCheck,1): " & Right(i_valueCheck,1) & vbCrLf & vbCrLf
checkTextFunction = indexOFirstSpaceFromTheEnd
End Function
but i don't find the first occurrence with the lines
whereSpace = InStrRev(i_valueCheck, " ", 1)
WhereNewLine = InStrRev(i_valueCheck, vbCrLf,1)
i get always 0.
Someone have idea?
******* I edit my question !!!!.
Thanks,
Tal

vbCrLf is actually 2 characters, so you want to specify Right(i_valueCheck, 2) = vbCrLf
If the character is not in the string, then InStrRev will return 0.. which would mean it is always the first occurrence. The second If statement should be a little more explicit in terms of the values of the variables.
Since you're not initializing indexOFirstSpaceFromTheEnd... If there are no vbCrLf or " " characters- it will remain empty. Therefore you should add a check in order to return a value every time... regardless of the string. I picked one million arbitrarily.
Function checkTextFunction(ByRef i_valueCheck)
Dim whereSpace
Dim whereNewLine
Dim indexOFirstSpaceFromTheEnd
If Right(i_valueCheck,1) = " " Or Right(i_valueCheck,2) = vbCrLf Then
indexOFirstSpaceFromTheEnd = -1
Else
whereSpace = InStrRev(i_valueCheck, " ", -1, 0)
whereNewLine = InStrRev(i_valueCheck, vbCrLf, -1, 0)
If whereSpace > 0 And (whereSpace < whereNewLine Or whereNewLine = 0) Then
indexOFirstSpaceFromTheEnd = whereSpace
ElseIf whereNewLine > 0 And (whereNewLine < whereSpace Or whereSpace = 0) Then
indexOFirstSpaceFromTheEnd = whereNewLine
End If
End If
If indexOFirstSpaceFromTheEnd = vbEmpty Then indexOFirstSpaceFromTheEnd = 1000000
WriteLogFileLine "indexOFirstSpaceFromTheEnd: " & _
indexOFirstSpaceFromTheEnd & _
" Right(i_valueCheck,1): " & _
Right(i_valueCheck,1) & vbCrLf & vbCrLf
checkTextFunction = indexOFirstSpaceFromTheEnd
End Function
This should help you get started... realistically- if you want to find the first occurrence of vbCrLf or " " then you're going to have to operate a While loop in order to keep checking (with InStrRev) that the index is actually the last occurrence.
For example: with the code above... look at the output of checkTextFunction(Space(2) & "test")

The final answer: if the last char in "i_valueCheck" is not space or vbCrLf it's find the first case(space or vbCrLf) from the end of "i_valueCheck".
Function checkTextFunction( i_valueCheck)
Dim whereSpace
Dim whereNewLine
Dim indexOFirstSpaceFromTheEnd
If Right(i_valueCheck,1) = " " Or Right(i_valueCheck,2) = vbCrLf Then
indexOFirstSpaceFromTheEnd = -1
Else
whereSpace = InStrRev(i_valueCheck, " ", -1, 0)
whereNewLine = InStrRev(i_valueCheck, vbCrLf, -1, 0)
If whereSpace > 0 And (whereSpace > whereNewLine Or whereNewLine = 0) Then
indexOFirstSpaceFromTheEnd = whereSpace
ElseIf whereNewLine > 0 And (whereNewLine > whereSpace Or whereSpace = 0) Then
indexOFirstSpaceFromTheEnd = whereNewLine
Else
indexOFirstSpaceFromTheEnd = -1
End If
End If
checkTextFunction = indexOFirstSpaceFromTheEnd End Function

Related

VB6 Run time error 424

I am getting error 424 on this line, can anyone help me please.
lblprvbal.Text = Val(NewItem.SubItems(11))
Private Sub cmdShow_Click()
'lblTotPur/lblTotPayRet/lblBalance
Dim strShow, mSlNo
Dim rsShow As New ADODB.Recordset
Dim NewItem As Variant
If Trim(txtCustomer.Text) = "" Then
MsgBox "Please select customer to proceed...", vbCritical, POPUP_COMP
Exit Sub
End If
Dim recCnt
pgrPartyLedger.Min = 0
recCnt = 0
'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser CASH PURCHASE RETURN
strShow = "select Count(*) as mCnt from VOUCHMST A,VOUCHDAT B, Prevbal C "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
'strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn
recCnt = rsShow("mCnt")
rsShow.Close
pgrPartyLedger.Max = recCnt + 1
'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser
strShow = "select A.Id,A.cmnt,A.ADV,A.VNO,A.DATED,B.IDNO,B.IDNAME,B.AMOUNT,B.DR_CR,B.VNARRATION,A.REMARKS,B.CQ_TYPE, B.BANKNAME, B.BANKBRANCH, B.CQ_NO, C.amnt from VOUCHMST A,VOUCHDAT B, Prevbal C "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn
Dim mPur, mPayRet, mAnyAdv, mTempVNO
mPur = 0
mPayRet = 0
mAnyAdv = 0
mSlNo = 1
ShowPaymentHeader
Do While Not rsShow.EOF
mTempVNO = rsShow("VNO")
Set NewItem = listViewPayment.ListItems.Add(, "C" & mSlNo, Format(rsShow("DATED"), "dd/MM/yyyy"))
NewItem.SubItems(1) = mTempVNO
NewItem.SubItems(2) = IIf(IsNull(rsShow("IDNAME")), "", CommaFilterText(rsShow("IDNAME"), 1))
NewItem.SubItems(11) = rsShow("amnt")
If Trim(rsShow("REMARKS")) = "CASH SALE" Then
NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT"))
NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
ElseIf Trim(rsShow("REMARKS")) = "CREDIT SALE" Then
mAnyAdv = ShowPartialAdvance(rsShow("VNO"))
NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT") + Val(mAnyAdv))
If Val(mAnyAdv) > 0 Then
NewItem.SubItems(4) = FormatTakaPaisa(mAnyAdv)
Else
NewItem.SubItems(4) = ""
End If
Else
NewItem.SubItems(3) = ""
NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
NewItem.SubItems(7) = rsShow("CQ_TYPE")
NewItem.SubItems(8) = rsShow("BANKNAME")
NewItem.SubItems(9) = rsShow("BANKBRANCH")
NewItem.SubItems(10) = rsShow("CQ_NO")
NewItem.SubItems(13) = "" & rsShow("cmnt")
End If
NewItem.SubItems(6) = rsShow("IDNO")
mPur = mPur + Val(NewItem.SubItems(3))
mPayRet = mPayRet + Val(NewItem.SubItems(4))
NewItem.SubItems(5) = rsShow("REMARKS")
NewItem.SubItems(12) = GetVoucherRefNo(mTempVNO)
pgrPartyLedger.Value = mSlNo
mSlNo = mSlNo + 1
rsShow.MoveNext
Loop
rsShow.Close
lblprvbal.Text = Val(NewItem.SubItems(11))
lblTotPur.Caption = FormatTakaPaisa(mPur) + Val(lblprvbal.Text)
lblTotPayRet.Caption = FormatTakaPaisa(mPayRet)
lblBalance.Caption = FormatTakaPaisa(mPur - mPayRet) + Val(lblprvbal.Text)
pgrPartyLedger.Value = 0
End Sub
Looks like lblprvbal isn't an object. Meaning, you don't have a TextBox called lblprvbal in your form, even if you think you do. Maybe because its real name is lblPrvBal? That would be consistent with your other object names. As a side note, you probably don't want to start a TextBox with lbl, which suggests it's a label.
Try below. value in the sub item is null and hence the error.
If IsDBNull(NewItem.SubItems(11)) Then
lblprvbal.Text = ""
Else
lblprvbal.Text = Val(NewItem.SubItems(11))
End If
Check if not NewItem is Nothing.

Webcam application to save image to database

I want to create a webcam application that can save image to database. My code is from the internet. My code can only save binary but I guess my conversion was incorrect because I can't retrieve them from the database.
Here is my Code:
Private Sub cmdsave_Click()
OpenDB
rs.Open "tblimg", db, adOpenKeyset, adLockPessimistic, adCmdTable
Dim bytData() As Byte, PicInfo As BITMAP
If Dir(App.path & "\myPic", vbDirectory) = "" Then MkDir (App.path & "\myPic")
File1.path = App.path & "\myPic"
'File1.Pattern = "*.bmp"
File1.Pattern = "*.jpg"
File1.Refresh
Dim Maxnum As Integer, ii As Integer
For ii = 0 To File1.ListCount - 1
If Left(File1.List(ii), 1) = "p" Then
If CInt(Mid(File1.List(ii), 2, Len(File1.List(ii)) - 4)) > Maxnum Then
Maxnum = CInt(Mid(File1.List(ii), 2, Len(File1.List(ii)) - 4))
End If
End If
Next
Picture1.Picture = Image1.Picture
'SavePicture Image1.Picture, App.Path & "\myPic\p" & Maxnum + 1 & ".bmp"
SAVEJPEG App.path & "\myPic\p" & Maxnum + 1 & ".jpg", 100, Me.Picture1
ReDim bytData((PicInfo.bmHeight * PicInfo.bmWidth)) As Byte
With rs
.AddNew
.Fields("Picture").AppendChunk bytData
.Fields("Desc") = Label2.Caption
.Update
End With
Set rs = Nothing
db.Close: Set db = Nothing
End Sub
Hope this code give you idea of what you want to achive
Picture3.Visible = True
SavePicture Picture1.Picture, App.Path & "\Emp Photo\" & UCase(Trim(G_EmpCode)) _ & ".jpg"
Picture3.Picture = LoadPicture(App.Path & "\Emp Photo\" & UCase(Trim(G_EmpCode)) & ".jpg")
Picture2.Picture = LoadPicture(App.Path & "\Emp Photo\" & UCase(Trim(G_EmpCode)) & ".jpg")
FrmEmployee.Image1.Picture = Picture2.Picture
CCTVImagePath = App.Path & "\Emp Photo\" & UCase(Trim(G_EmpCode)) & ".jpg"
Call cmdClose_Click
Call CmdStart_Click
If CCTVImagePath <> "" Then
ImagePath = CCTVImagePath
m_imgfile = CCTVImagePath
End If
If FileSystemObj.FileExists(ImagePath) = True Then
Set strStream = New ADODB.Stream
strStream.Type = adTypeBinary
strStream.Open
Sourcefile = ImagePath
strStream.LoadFromFile Sourcefile
CCTVImagePath = ""
End If
CCTVImagePath = ""

VB Script that will manipulate a file name

Ok, like many other people, I am a noob on VB Scripting. What I am trying to do is create a VB Script that will manipulate a file name from Fulton A1032-CCC Adamsville to just A1032-CCC. I have browsed many site trying to find the answer but only came up with on that halfway worked.
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='H:\Darrell 2014 folder\Distview Wiki Revamp\To'} Where " _
& "ResultClass = CIM_DataFile")
For Each objFile In colFiles
strPath = objFile.Drive & objFile.Path
strExtension = objFile.Extension
strFileName = objFile.FileName
If Left(strFileName, 7) = "Fulton " Then
intLength = Len(strFileName)
strFileName = Right(strFileName, intLength - 7)
End If
If Right(strFileName, 10) = " Adamsville" Then
intLength = Len(strFileName)
strFileName = Left(strFileName, intLength - 10)
End If
strNewName = strPath & strFileName & "." & strExtension
errResult = objFile.Rename(strNewName)
Next
Please Help
Why not just use the replace function instead? For example:
Dim fileName As String
fileName = "Fulton A1032-CCC Adamsville"
fileName = Replace(fileName, "Fulton ", "")
fileName = Replace(fileName, " Adamsville", "")
MsgBox fileName
The output is A1032-CCC. This also works if either or both of the search strings don't exist.
Learn to count:
>> WScript.Echo Len(" Adamsville")
>>
11
>>
or write a function:
>> Function endsWith(b, t)
>> endsWith = Right(b, len(t)) = t
>> End Function
>> WScript.Echo CStr(endsWith("Fulton A1032-CCC Adamsville", " Adamsville"))
>>
True
Update wrt downvotes:
As the downvotes indicate that there are at least two people who can't count either:
Option Explicit
Function qq(s) : qq = """" & s & """" : End Function
Dim strFileName : strFileName = "Fulton A1032-CCC Adamsville"
Dim intLength
WScript.Echo 0, qq(strFileName)
' assume the structure of the input data is:
' <todelete+blank><tokeep><blank+todelete>
WScript.Echo 1, qq(Split(strFileName)(1))
' the ot's code 'works' if you count correctly
If Left(strFileName, 7) = "Fulton " Then
intLength = Len(strFileName)
strFileName = Right(strFileName, intLength - 7)
End If
If Right(strFileName, 11) = " Adamsville" Then
intLength = Len(strFileName)
strFileName = Left(strFileName, intLength - 11)
End If
WScript.Echo 2, qq(strFileName)
output:
cscript 25689666.vbs
0 "Fulton A1032-CCC Adamsville"
1 "A1032-CCC"
2 "A1032-CCC"

VBS Script for listing out Outlook Profile Info

I have found some code on the Internet for listing out Outlook Profile Info and I would like to it, but it gives the error: Type mismatch:'[string: "A"]', at line 74 (code 800A000D). I don't know why it's not working.
Here is the code:
Option Explicit
Const HKEY_CURRENT_USER = &H80000001
Const r_PSTGuidLocation = "01023d00"
Const r_MasterConfig = "01023d0e"
Const r_PSTCheckFile = "00033009"
Const r_PSTFile = "001f6700"
Const r_keyMaster = "9207f3e0a3b11019908b08002b2a56c2"
Const r_ProfilesRoot = "Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles"
Const r_DefaultProfileString = "DefaultProfile"
Dim oReg:Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
Dim arrSubKeys, subkey, strValue, i, pstFile, arrPSTs, DefaultProfileName
oReg.GetStringValue HKEY_CURRENT_USER,r_ProfilesRoot,r_DefaultProfileString,DefaultProfileName
GetPSTsForProfile(DefaultProfileName)
'_____________________________________________________________________________________________________________________________
Function GetPSTsForProfile(p_profileName)
Dim strHexNumber, strPSTGuid, strFoundPST
oReg.GetBinaryValue HKEY_CURRENT_USER,r_ProfilesRoot & "\" & p_profileName & "\" & r_keyMaster,r_MasterConfig,strValue
If IsUsableArray (strValue) Then
For Each i In strValue
If Len(Hex(i)) = 1 Then
strHexNumber = CInt("0") & Hex(i)
Else
strHexNumber = Hex(i)
End If
strPSTGuid = strPSTGuid + strHexNumber
If Len(strPSTGuid) = 32 Then
If IsAPST(r_ProfilesRoot & "\" & p_profileName & "\" & strPSTGuid) Then
Wscript.Echo PSTFileName(r_ProfilesRoot & "\" & p_profileName & "\" & _
PSTlocation(r_ProfilesRoot & "\" & p_profileName & "\" & strPSTGuid))
End If
strPSTGuid = ""
End If
Next
End If
End Function
'______________
'_____________________________________________________________________________________________________________________________
Function GetSize(zFile)
Dim objFSO:Set objFSO = CreateObject("Scripting.FileSystemObject")
dim objFile:Set objFile = objFSO.GetFile(zFile)
GetSize = ConvertSize(objFile.Size)
End Function
'_____________________________________________________________________________________________________________________________
Function ConvertSize(Size)
Do While InStr(Size,",") 'Remove commas from size
CommaLocate = InStr(Size,",")
Size = Mid(Size,1,CommaLocate - 1) & _
Mid(Size,CommaLocate + 1,Len(Size) - CommaLocate)
Loop
Dim Suffix:Suffix = " Bytes"
If Size >= 1024 Then suffix = " KB"
If Size >= 1048576 Then suffix = " MB"
If Size >= 1073741824 Then suffix = " GB"
If Size >= 1099511627776 Then suffix = " TB"
Select Case Suffix
Case " KB" Size = Round(Size / 1024, 1)
Case " MB" Size = Round(Size / 1048576, 1)
Case " GB" Size = Round(Size / 1073741824, 1)
Case " TB" Size = Round(Size / 1099511627776, 1)
End Select
ConvertSize = Size & Suffix
End Function
'_____________________________________________________________________________________________________________________________
Function IsAPST(p_PSTGuid)
Dim x, P_PSTGuildValue
Dim P_PSTCheck:P_PSTCheck=0
IsAPST=False
oReg.GetBinaryValue HKEY_CURRENT_USER,p_PSTGuid,r_PSTCheckFile,P_PSTGuildValue
If IsUsableArray (P_PSTGuildValue) Then
For Each x in (P_PSTGuildValue)
P_PSTCheck = P_PSTCheck + Hex(x)
Next
End If
If P_PSTCheck=20 Then IsAPST=True
End Function
'_____________________________________________________________________________________________________________________________
Function PSTlocation(p_PSTGuid)
Dim y, P_PSTGuildValue
oReg.GetBinaryValue HKEY_CURRENT_USER,p_PSTGuid,r_PSTGuidLocation,P_PSTGuildValue
If IsUsableArray (P_PSTGuildValue) Then
For Each y In P_PSTGuildValue
If Len(Hex(y)) = 1 Then
PSTlocation = PSTlocation & CInt("0") & Hex(y)
Else
PSTlocation = PSTlocation & Hex(y)
End If
Next
End If
End Function
'_____________________________________________________________________________________________________________________________
Function PSTFileName(p_PSTGuid)
Dim z, P_PSTName
Dim strString : strString = ""
oReg.GetBinaryValue HKEY_CURRENT_USER,p_PSTGuid,r_PSTFile,P_PSTName
If IsUsableArray (P_PSTName) Then
For Each z in P_PSTName
If z > 0 Then strString = strString & Chr(z)
Next
End If
PSTFileName = strString
End Function
'_________________________________________________________________________________________________________
Function ExpandEvnVariable(ExpandThis)
Dim objWSHShell:Set objWSHShell = CreateObject("WScript.Shell")
ExpandEvnVariable = objWSHShell.ExpandEnvironmentStrings("%" & ExpandThis & "%")
End Function
'_________________________________________________________________________________________________________
Function IsUsableArray(rvnt)'-- Use this function to test for a Null, Empty or an undimensioned array.'-- Useful b/c some interfaces can hold properties for which if they have a'-- value will be an Array but may also be Null or an undimensioned Array.
'-- It assumes that a Null or Empty could potentially be an array but not yet dimensioned. '-- It returns -1 if it is passed a string, long, etc...'-- It returns 0 for an empty array or the number of elements in the first dimension.
IsUsableArray = 0
If (VarType(rvnt) And 8192) = 8192 Then
IsUsableArray = UBound(rvnt) - LBound(rvnt) + 1
Else
If Not (IsEmpty(rvnt) Or IsNull(rvnt)) Then IsUsableArray = -1
End If
End Function
The script works on my system if i correct the extra space at line 8 (Windows Messaging Subsystem)
It is a big script for what it offers, see here for a smaller one which offers more using the free to download library Redemption at http://www.dimastr.com/redemption/home.htm which is what CDO should have been.
set Session = CreateObject("Redemption.RDOSession")
const skUnknown = 0, olStoreANSI = 1, olStoreUnicode = 2, skPrimaryExchangeMailbox = 3, skPublicFolders = 5, skDelegateExchangeMailbox = 4
Session.Logon
for each Store in Session.Stores
if (Store.StoreKind = olStoreANSI) then
wscript.echo Store.Name & " - " & Store.PstPath & " " & Store.Name
elseif (Store.StoreKind = olStoreUnicode) Then
wscript.echo Store.Name & " - " & Store.PstPath
ElseIf (Store.StoreKind = skPrimaryExchangeMailbox) or (Store.StoreKind = skDelegateExchangeMailbox) or (Store.StoreKind = skPublicFolders) Then
wscript.echo Store.Name & " - " & Store.ServerDN
Else
wscript.echo Store.Name & " - " & Store.StoreKind
End If
next

Need Visual Studio macro to add banner to all C# files

Can someone post a Visual Studio macro which goes through all C# source files in a project and adds a file banner? Extra credit if it works for any type of source file (.cs, .xaml, etc).
Here you go, I provide an example for .cs and .vb but shouldn't be hard for you to adjust it to your other file type needs: Edited to recursively add header to sub-folders
Sub IterateFiles()
Dim solution As Solution = DTE.Solution
For Each prj As Project In solution.Projects
IterateProjectFiles(prj.ProjectItems)
Next
End Sub
Private Sub IterateProjectFiles(ByVal prjItms As ProjectItems)
For Each file As ProjectItem In prjItms
If file.SubProject IsNot Nothing Then
AddHeaderToItem(file)
IterateProjectFiles(file.ProjectItems)
ElseIf file.ProjectItems IsNot Nothing AndAlso file.ProjectItems.Count > 0 Then
AddHeaderToItem(file)
IterateProjectFiles(file.ProjectItems)
Else
AddHeaderToItem(file)
End If
Next
End Sub
Private Sub AddHeaderToItem(ByVal file As ProjectItem)
DTE.ExecuteCommand("View.SolutionExplorer")
If file.Name.EndsWith(".cs") OrElse file.Name.EndsWith(".vb") Then
file.Open()
file.Document.Activate()
AddHeader()
file.Document.Save()
file.Document.Close()
End If
End Sub
Private Sub AddHeader()
Dim cmtHeader As String = "{0} First Line"
Dim cmtCopyright As String = "{0} Copyright 2008"
Dim cmtFooter As String = "{0} Footer Line"
Dim cmt As String
Select Case DTE.ActiveDocument.Language
Case "CSharp"
cmt = "//"
Case "Basic"
cmt = "'"
End Select
DTE.UndoContext.Open("Header Comment")
Dim ts As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection)
ts.StartOfDocument()
ts.Text = String.Format(cmtHeader, cmt)
ts.NewLine()
ts.Text = String.Format(cmtCopyright, cmt)
ts.NewLine()
ts.Text = String.Format(cmtFooter, cmt)
ts.NewLine()
DTE.UndoContext.Close()
End Sub
Visual Studio macro to add file headers
Here is the jist of it. No, I have not debugged this, that is an excercise for the reader. And, this is done off the top of my head. (Except the File commenter...That's a real Macro that I use).
function CommentAllFiles
option explicit
Dim ActiveProjectFullName
Dim dte80 As EnvDTE80.Solution2
ActiveProjectFullName = dte80.Projects.Item(0).FullName
If ActiveProjectFullName = "" Then
MsgBox("No project loaded!")
Exit Sub
End If
Err.Number = 0
doc.Open(ActiveProjectFullName, "Text", True)
If Err.Number <> 0 Then
MsgBox("Open " + ActiveProjectFullName + " failed: " & Hex(Err.Number))
Exit Sub
End If
ActiveDocument.Goto(1, 1, vsMovementOptions.vsMovementOptionsMove)
' Build search string
Dim SearchString
Dim vsFindOptionsValue As Integer
SearchString = "^SOURCE=.*" + dn + "$"
while ActiveDocument.Selection.FindText(SearchString, vsFindOptions.vsFindOptionsFromStart + vsFindOptions.vsFindOptionsRegularExpression)
Dim TheFile
TheFile = ActiveDocument.Selection.Text
TheFile = Mid(TheFile, 8)
doc.Open(TheFile)
wend
ActiveDocument.Close()
end function
Tried and true "Flower Box" adder:
Function IsClassDef()
Dim ColNum
Dim LineNum
Dim sText
sText = ActiveDocument.Selection.ToString()
If sText = "" Then
'ActiveDocument.Selection.WordRight(dsExtend)
'sText = ActiveDocument.Selection
'sText = ucase(trim(sText))
End If
If (sText = "CLASS") Then
IsClassDef = True
Else
IsClassDef = False
End If
End Function
Sub AddCommentBlock()
'DESCRIPTION: Add Commecnt block to header, CPP files and Class Defs
AddCPPFileDesc()
End Sub
Sub AddCPPFileDesc()
'DESCRIPTION: Add File desc block to the top of a CPP file
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
Dim bOk, sExt, IsCpp, IsHdr, sHeader, IsCSharp
bOk = True
IsCpp = False
IsCSharp = False
If ActiveDocument.Selection.CurrentLine > 10 Then
If MsgBox("You are not at the top of the file. Are you sure you want to continue?", vbYesNo + vbDefaultButton2) = vbNo Then
bOk = False
End If
End If
If (bOk) Then
sExt = ucase(right(ActiveDocument.Name, 4))
IsCpp = sExt = ".CPP"
IsHdr = Right(sExt, 2) = ".H"
IsCSharp = sExt = ".CS"
If (IsCpp) Then
sHeader = left(ActiveDocument.Name, len(ActiveDocument.Name) - 3) + "h"
FileDescTopBlock(1)
editPoint.Insert("#include " + Chr(34) + "StdAfx.h" + Chr(34) + vbLf)
editPoint.Insert("#include " + Chr(34) + sHeader + Chr(34) + vbLf)
ElseIf (IsCSharp) Then
FileDescTopBlock(1)
Else
If IsHdr Then
'If IsCLassDef() Then
'AddClassDef()
'Else
AddHeaderFileDesc()
'End If
Else
FileDescTopBlock(1)
End If
End If
End If
End Sub
Sub AddHeaderFileDesc()
FileDescTopBlock(0)
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
editPoint.Insert("#pragma once" + vbLf)
End Sub
Sub FileDescTopBlock(ByVal HasRevHistory)
'DESCRIPTION: Add File desc block to the top of a CPP file
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
ActiveDocument.Selection.EndOfLine()
Dim sComment
sComment = ActiveDocument.Selection.ToString()
If Left(sComment, 2) = "//" Then
ActiveDocument.Selection.Delete()
sComment = LTrim(Mid(sComment, 3))
Else
sComment = ""
End If
Dim sLineBreak
Dim sFileName
Dim sBlock
sLineBreak = "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"
sFileName = ActiveDocument.Name
ActiveDocument.Selection.StartOfDocument()
sBlock = sLineBreak & vbLf & _
"// File : " & sFileName & vbLf & _
"// Author : Larry Frieson" & vbLf & _
"// Desc : " & sComment & vbLf & _
"// Date : " & CStr(Now.Date()) & vbLf & _
"//" & vbLf & _
"// Copyright © 20" + Right(CStr(Now.Year.ToString()), 2) + " MLinks Technologies. All rights reserved" + vbLf
If (HasRevHistory > 0) Then
sBlock = sBlock & _
"//" & vbLf & _
"// Revision History: " & vbLf & _
"// " & CStr(Now) & " created." & vbLf & _
"// " & vbLf
End If
sBlock = sBlock + sLineBreak + vbLf
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
editPoint.Insert(sBlock)
End Sub
Hope this helps, or at least gives you some ideas. Again, I didn't test/debug the "source file looper", I figure you can handle that.
Larry

Resources