Function returns empty result - vb6

I am getting empty msgBox when i call the function . Have a look on code as bellow
Public Function Custom(ByVal TableName As String, _
ByVal EmployeeCode As String, ByVal FieldName As String, ByVal DataToCheck As String, _
Optional ByVal CodeFieldName As String = Empty, Optional ByVal CodeFieldValue As String = Empty) As Boolean
Dim lstrSQL1 As String
Dim lrsTemp1 As ADODB.Recordset
lstrSQL1 = " Select " & FieldName & " from " & TableName & " Where ID_CARD_NO =" & DataToCheck & ""
'MsgBox (lstrSQL1)
If Len(Trim$(CodeFieldName)) <> 0 And Len(Trim$(CodeFieldValue)) <> 0 Then
lstrSQL1 = lstrSQL1 & " AND " & CodeFieldName & " <> '" & CodeFieldValue & "'"
End If
Set lrsTemp1 = cObjDBConn.ExecuteSQL(lstrSQL1)
If lrsTemp1 Is Nothing Then
Custom = False
ElseIf Not (lrsTemp1.BOF And lrsTemp1.EOF) Then
Custom = True
ElseIf lrsTemp1.RecordCount = 0 Then
Custom = False
Else
Custom = False
End If
If lrsTemp1.State = adStateOpen Then lrsTemp1.Close
Set lrsTemp1 = Nothing
Exit Function
ErrorHandle:
Custom = False
End Function
The calling code is here:
If gobjValidation.Custom(fstrTableName, gEmployeeCode, "EMPLOYEE_CODE", _
Trim$(TxtIDcardNo.text)) = True Then
MsgBox (gEmployeeCode)
Call MessageBox("This ID Number is already existing for another employee. Cannot enter duplicate number!Using By Employee Code:" & gEmployerCode & " ", OKOnly, Information, DefaultButton1, Me.Caption)
sstInformationTab.Tab = 0

As #Arvo said, you need to make youre EmployeeCode variable ByRef, then assign it a value in your function Custom()
Public Function Custom(ByVal TableName As String, _
**ByRef EmployeeCode As String**, ByVal FieldName As String, ByVal DataToCheck As String, _
Optional ByVal CodeFieldName As String = Empty, Optional ByVal CodeFieldValue As String = Empty) As Boolean
Dim lstrSQL1 As String
Dim lrsTemp1 As ADODB.Recordset
lstrSQL1 = " Select " & FieldName & " from " & TableName & " Where ID_CARD_NO =" & DataToCheck & ""
'MsgBox (lstrSQL1)
If Len(Trim$(CodeFieldName)) <> 0 And Len(Trim$(CodeFieldValue)) <> 0 Then
lstrSQL1 = lstrSQL1 & " AND " & CodeFieldName & " <> '" & CodeFieldValue & "'"
End If
Set lrsTemp1 = cObjDBConn.ExecuteSQL(lstrSQL1)
If lrsTemp1 Is Nothing Then
Custom = False
ElseIf Not (lrsTemp1.BOF And lrsTemp1.EOF) Then
Custom = True
**lrsTemp1.MoveFirst**
**EmployeeCode = lrsTemp1.Fields("EMPLOYEE_CODE")**
ElseIf lrsTemp1.RecordCount = 0 Then
Custom = False
Else
Custom = False
End If
If lrsTemp1.State = adStateOpen Then lrsTemp1.Close
Set lrsTemp1 = Nothing
Exit Function
ErrorHandle:
Custom = False
End Function
The double asterisks are just to highlight the changes I made to your original code.

Related

Out of Memory error when trying to connect to oracle database (VB6)

when I m trying to set Recordset using oracle connection string, I m getting OUt of memory error.
on line "rsLIS.Open sql, gConnLIS, adOpenStatic, adLockReadOnly"
However some time it works like once in 5-6 attempts
but when it works it gives error on some other line
on line "If rsLink.Fields(2).value = rsLIS.Fields(1).value Then"
here are the things which I tried :
instead of directly using recordset, I tried to create array (GetRows) method.
Even though recordset count is 26 but UBound of array is showing 1
I have trying changing 3rd argument value from static to forward only
in line ""rsLIS.Open sql, gConnLIS, adOpenStatic, adLockReadOnly""
it also didn't work, it was showing recordset.count as 0
Did try after restarting the client system still same
I m getting this error on client side and since at my place I don't have development environment to debug
Error is "OUT OF MEMORY"
Public Function GetResults_New(MachName As String, patid As String, bCheckDate As Boolean, SendAssay As Boolean) As ADODB.Recordset
On Error GoTo errdesc
Call ShowTempMsg("Line 1")
Dim bXVar As Boolean
Dim i, j As Integer
Dim tmplis, tmporder
Dim tmpresult
bXVar = False
Dim rec_result As New ADODB.Recordset
Dim rsLink As New ADODB.Recordset
Dim rsLIS As New ADODB.Recordset
Dim xSampleIdType As String
gAppPath = AddEditINIfile("VAHSIF.INI", "IF", "sLinkPath", "")
xSampleIdType = AddEditINIfile(gAppPath & "\sLinkConfig.ini", MachName, "SampleIdType", "SampleId1", False)
Call Open_Connection
Call Open_Connection_LIS
rec_result.CursorLocation = adUseClient
If SendAssay = True Then
rec_result.Fields.Append "machineparamid", adBSTR, 50
rec_result.Fields.Append "Assayno", adBSTR, 50
rec_result.Fields.Append "SType", adBSTR, 50
rec_result.Fields.Append "Dilution", adBSTR, 50
Else
rec_result.Fields.Append "machineparamid", adBSTR, 50
rec_result.Fields.Append "SType", adBSTR, 50
rec_result.Fields.Append "Dilution", adBSTR, 50
End If
rec_result.Open
\
'Link Query For Mapped Params.
sql = "SELECT EquipParamMapping.EquipId, EquipParamMapping.EquipParamCode, EquipParamMapping.LISParamCode, EquipParamMapping.EquipAssayNo from EquipParam, EquipParamMapping where equipParam.equipid = equipparammapping.equipid and equipparam.equipparamcode = equipparammapping.equipparamcode and EquipParam.EquipID = '" & MachName & "' and EquipParam.isProgram = 'Y'"
**rsLink.Open sql, gConn, adOpenStatic, adLockReadOnly**
If enumConnTo = connOracle Then
sql = "select " & xSampleIdType & " , LIS_Param_Code From SL_21CI_View_sampleid_Orders where " & xSampleIdType & " || SuffixCode = '" & patid & "' and isApplicable <> 'N' "
Else
sql = "select " & xSampleIdType & " , LIS_Param_Code From SL_21CI_View_sampleid_Orders where " & xSampleIdType & " + cast(SuffixCode as varchar(20)) = '" & patid & "' and isApplicable <> 'N' "
End If
rsLIS.Open sql, gConnLIS, adOpenStatic, adLockReadOnly
While Not rsLIS.EOF
If bXVar = True Then
rsLink.MoveFirst
bXVar = False
End If
While Not rsLink.EOF
bXVar = True
**If rsLink.Fields(2).value = rsLIS.Fields(1).value Then**
If SendAssay = True Then
rec_result.AddNew
rec_result("machineparamid") = rsLink.Fields("EquipParamCode")
rec_result("Assayno") = rsLink.Fields("EquipAssayNo")
rec_result("SType") = " "
rec_result("Dilution") = "0"
rec_result.Update
rec_result.MoveFirst
Else
rec_result.AddNew
rec_result("machineparamid") = rsLink.Fields("EquipParamCode")
rec_result("SType") = " "
rec_result("Dilution") = "0"
rec_result.Update
rec_result.MoveFirst
End If
GoTo NextParam
End If
rsLink.MoveNext
Wend
NextParam:
rsLIS.MoveNext
Wend
Set GetResults_New = rec_result
Exit Function
errdesc:
Call InsertIntoLogWithFileName("Transaction.GetResults_New" & vbNewLine & sql & vbNewLine & err.Description & "ErrLine : " & ErrLine)
End Function
Thanks
That still leaves the question on which line the error occurs. Also: "it also didn't work, it was showing recordset.count as 0". The RecordSet.Count property depends on the provider. Use a function similar to this instead:
Public Function RecordCount(ByVal cn As ADODB.Connection, ByVal sTable As String) As Long
Dim sSQL As String, lRetVal as Long
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
sSQL = "SELECT COUNT(1) AS RecCount FROM " & sTable & ";"
Call rs.Open(sSQL, cn)
If Not (rs.BOF And rs.EOF) Then
lRetVal = rs.Fields("RecCount").Value
Else
lRetVal = -1
End If
Call rs.Close
Set rs = Nothing
RecordCount = lRetVal
End Function
The .Count property might also very well be the cause of the Out of memory error, as I seem to remember that for determing the number of records, it loads all records (from the server) to count them. But I might be wrong there.

Check for existing DSN before creating it with vb6 code

i have done a connection using DSN, in which i have created a DSN throgh program. In that i have called a function to create a DSN, I dont want to call that function ecerytime i run the software, Instead i want to check whether dsn with the same name is already exist in the system or not, if it is not exist then only call to the function`
Public Sub ConnectDB(Con As ADODB.Connection)
Call CreatSQLDSN("TRDSN", VarSrvNm, VarDbName)
If Cn.State = 1 Then Cn.Close
On Error Resume Next
Con.ConnectionString = "Provider=MSDASQL.1;Persist Security Info=False;User ID=sa;Data Source=TRDSN;Initial Catalog='" & VarDbName & "'"
Con.Open Con.ConnectionString
If Err.Number <> 0 Then
If Err.Number = -2147467259 Then
If MsgBox(ServerName & " Server not Found. Connect to Other Server?", vbQuestion + vbDefaultButton2 + vbYesNo, "") = vbYes Then
PrintFile = Trim(Left(FindWindowPath, 3) & "DosPrint.Bat")
FileSystemObject.CreateTextFile PrintFile, True
Set TextStream = FileSystemObject.OpenTextFile(PrintFile, ForAppending)
TextStream.WriteLine "Del " & Left(FindWindowPath, 3) & "ServerName.dat"
TextStream.Close
Shell PrintFile, vbHide
End If
End
Else
If MsgBox(Err.Description, vbQuestion + vbOKOnly, "") = vbOK Then
Cancel = True
Exit Sub
End If
End If
End If
0
End Sub
Public Function CreatSQLDSN(SqlDsnName As String, SqlServerName As String, SqlDataName As String)
Dim Ret%, Driver$, Attributes$
Driver = "SQL Server" & Chr(0)
Attributes = "Server=" & SqlServerName & Chr(0)
Attributes = Attributes & "DSN=" & SqlDsnName & Chr(0)
Attributes = Attributes & "Database=" & SqlDataName & Chr(0)
Ret = SQLConfigDataSource(vbAPINull, ODBC_Add_User_DSN, Driver, Attributes)
'ret is equal to 1 on success and 0 if there is an error
If Ret <> 1 Then
MsgBox "User DSN Creation Failed"
End If
End Function`
A couple of options come to mind when needing to know if a DSN exists. You could either read through the Registry, or leverage your existing API call. I prefer the second option. It seems like a cleaner way to check for the existence of the DSN. Here is an example of what I am talking about:
Option Explicit
Private Declare Function SQLConfigDataSource Lib "ODBCCP32.DLL" (ByVal hwndParent As Long, ByVal fRequest As Long, ByVal lpszDriver As String, ByVal lpszAttributes As String) As Long
Private Const ODBC_ADD_DSN = 1
Private Const ODBC_CONFIG_DSN = 2
Private Const ODBC_REMOVE_DSN = 3
Private Const ODBC_ADD_SYS_DSN = 4
Private Const ODBC_CONFIG_SYS_DSN = 5
Private Const ODBC_REMOVE_SYS_DSN = 6
Private Const ODBC_REMOVE_DEFAULT_DSN = 7
Private Sub cmdCreate_Click()
Dim VarSrvNm As String
Dim VarDbName As String
VarSrvNm = "MyServer"
VarDbName = "MyDB"
If Not SQLDSNExists("TRDSN", VarSrvNm, VarDbName) Then
If Not CreateSQLDSN("TRDSN", VarSrvNm, VarDbName) Then
MsgBox "User DSN Creation Failed"
End If
End If
End Sub
Public Function CreateSQLDSN(SqlDsnName As String, SqlServerName As String, SqlDataName As String) As Boolean
Dim Ret%, Driver$, Attributes$
Driver = "SQL Server" & Chr(0)
Attributes = "Server=" & SqlServerName & Chr(0)
Attributes = Attributes & "DSN=" & SqlDsnName & Chr(0)
Attributes = Attributes & "Database=" & SqlDataName & Chr(0)
Ret = SQLConfigDataSource(0&, ODBC_ADD_DSN, Driver, Attributes)
'ret is equal to 1 on success and 0 if there is an error
CreateSQLDSN = (Ret = 1)
End Function
Public Function SQLDSNExists(SqlDsnName As String, SqlServerName As String, SqlDataName As String) As Boolean
Dim Ret%, Driver$, Attributes$
Driver = "SQL Server" & Chr(0)
Attributes = "Server=" & SqlServerName & Chr(0)
Attributes = Attributes & "DSN=" & SqlDsnName & Chr(0)
Attributes = Attributes & "Database=" & SqlDataName & Chr(0)
Ret = SQLConfigDataSource(0&, ODBC_CONFIG_DSN, Driver, Attributes)
'ret is equal to 1 on success and 0 if there is an error
SQLDSNExists = (Ret = 1)
End Function
The main idea here is to try to modify the DSN you want to add. If the call fails, then the DSN does not exist.

VBS: How to get the filesize with special FileDialog?

Function FileDialog()
Dim oExec1: Set oExec1=CreateObject("WScript.Shell").Exec( "mshta.exe ""about:" & "<" & "input type=file id=FILE" & ">" & "<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>""" )
Dim sPathfile: sPathfile = oExec1.StdOut.ReadAll
sPathfile = Replace( sPathfile, vbCRLF, "" )
FileDialog = sPathfile
End Function
change to:
Function FileDialog(filesize)
filesize will return the value of bytes of the selected file
Read Function Statement (VBScript) document and pass the argument by reference as follows:
option explicit
On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim nFileSize: nFileSize = -1 ' for test that `byRef` declaration works
strResult = strResult & vbNewLine & FileDialog( nFileSize)
strResult = strResult & vbNewLine & nFileSize
Wscript.Echo strResult
Wscript.Quit
Function FileDialog( byRef xSize)
Dim oExec1
Set oExec1=CreateObject("WScript.Shell").Exec( "mshta.exe ""about:" & "<" & "input type=file id=FILE" & ">" & "<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>""" )
Dim sPathfile: sPathfile = oExec1.StdOut.ReadAll
sPathfile = Replace( sPathfile, vbCRLF, "" )
If Len(sPathfile) > 0 Then
With CreateObject("Scripting.FileSystemObject").GetFile(sPathfile)
xSize = .Size ' the size, in bytes, of the specified file
End With
Else
' No file chosen: red "×" or Esc or Cancel pressed
xSize = 0
End If
FileDialog = sPathfile
End Function
Read ByRef and ByVal Parameters article as well.

Sync outlook messages with vbscript

I have a vbscript that copy's Outlook 2003 messages into a folder in msg format.
The problems are:
I am getting "path too long" errors for some *.msg . I wish to avoid these erros and I don't know how. ' On Error Resume Next is already on the script.
I am getting only inbox messages, but I want all subfolders too;
How can I extract this in *.txt and not in *.msg, in order to become lighter?
Here is my atual script. Thanks for the help!
On Error Resume Next
Dim myNameSpace
Dim ofChosenFolder
Dim myOlApp
Dim myItem
Dim objItem
Dim myFolder
Dim strSubject
Dim strName
Dim strFile
Dim strReceived
Dim strSavePath
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set myOlApp = CreateObject("Outlook.Application")
Set myNameSpace = myOlApp.GetNamespace("MAPI")
Const olFolderInbox = 6
Set ofChosenFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
strSavePath = "c:\test\" 'OBS! use a \ at the end of the path
i = 1
For each Item in ofChosenFolder.Items
Set myItem = ofChosenFolder.Items(i)
strReceived = ArrangedDate(myitem.ReceivedTime)
' strSubject = myItem.Subject
strSubject = myitem.SenderName & "_" & myitem.Subject
strName = StripIllegalChar(strSubject)
strFile = strSavePath & strReceived & "_" & strName & ".msg"
If Not Len(strfile) > 256 then
myItem.SaveAs strfile, 3
Else
wscript.echo strfile & vbcrlf & "Path and filename too long."
End If
i = i + 1
next
Function StripIllegalChar(strInput)
'***************************************************
'Simple function that removes illegal file system
'characters.
'***************************************************
Set RegX = New RegExp
RegX.pattern = "[\" & chr(34) & "\!\#\#\$\%\^\&\*\(\)\=\+\|\[\]\{\}\`\'\;\:\<\>\?\/\,]"
RegX.IgnoreCase = True
RegX.Global = True
StripIllegalChar = RegX.Replace(strInput, "")
Set RegX = nothing
End Function
Function ArrangedDate(strDateInput)
'***************************************************
'This function re-arranges the date data in order
'for it to display in chronilogical order in a
'sorted list in the file system. It also removes
'illegal file system characters and replaces them
'with dashes.
'Example:
'Input: 2/26/2004 7:07:33 AM
'Output: 2004-02-26_AM-07-07-33
'***************************************************
Dim strFullDate
Dim strFullTime
Dim strAMPM
Dim strTime
Dim strYear
Dim strMonthDay
Dim strMonth
Dim strDay
Dim strDate
Dim strDateTime
Dim RegX
If not Left(strDateInput, 2) = "10" Then
If not Left(strDateInput, 2) = "11" Then
If not Left(strDateInput, 2) = "12" Then
strDateInput = "0" & strDateInput
End If
End If
End If
strFullDate = Left(strDateInput, 10)
If Right(strFullDate, 1) = " " Then
strFullDate = Left(strDateInput, 9)
End If
strFullTime = Replace(strDateInput,strFullDate & " ","")
If Len(strFullTime) = 10 Then
strFullTime = "0" & strFullTime
End If
strAMPM = Right(strFullTime, 2)
strTime = strAMPM & "-" & Left(strFullTime, 8)
strYear = Right(strFullDate,4)
strMonthDay = Replace(strFullDate,"/" & strYear,"")
strMonth = Left(strMonthDay, 2)
strDay = Right(strMonthDay,len(strMonthDay)-3)
If len(strDay) = 1 Then
strDay = "0" & strDay
End If
strDate = strYear & "-" & strMonth & "-" & strDay
'strDateTime = strDate & "_" & strTime
strDateTime = strDate
Set RegX = New RegExp
RegX.pattern = "[\:\/\ ]"
RegX.IgnoreCase = True
RegX.Global = True
ArrangedDate = RegX.Replace(strDateTime, "-")
Set RegX = nothing
End Function
You need to truncate the file name appropriately (strName)
Move your code that processes a folder into a sub that take fodler that takes folder as parameter and call it for ofChosenFolder as well as all of its child fodlers in the ofChosenFolder.Folders collection.
You are calling SaveAs..., 3 - 3 here is olMsg. Specify olTxt (= 0).
Off the top of my head:
Const olFolderInbox = 6
Set ofChosenFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
trSavePath = "c:\test\"
ProcessFolder ofChosenFolder, trSavePath
sub ProcessFolder(folder, path)
For each Item in folder.Items
strReceived = ArrangedDate(Item.ReceivedTime)
strSubject = Item.SenderName & "_" &Item .Subject
strName = StripIllegalChar(strSubject)
strFile = strSavePath & strReceived & "_" & strName & ".msg"
If Not Len(strfile) > 256 then
Item.SaveAs strfile, 3
Else
wscript.echo strfile & vbcrlf & "Path and filename too long."
End If
next
for each subfolder in folder.Folders
ProcessFolder(subfolder, trSavePath & subfolder.Name & "\"
next
end sub

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