Posts

Write Unicode text using VBA

Image
There are some ways to create and access Unicode files using VBA. The most straightforward way is to use the Microsoft Scripting Runtime library. The two following ways may be used to open a file for write operations: 'the scripting lib way Dim fs As New FileSystemObject, txt As TextStream Dim pth As String : pth = "d:\data.txt" Set txt = fs.CreateTextFile(pth, True, True) ''alternative way to open the textfile 'Set txt = fs.OpenTextFile(pth, ForWriting, True, TristateTrue) 'to write simply write the following in Unicode txt.WriteLine "test text" If we want to avoid using the Microsoft Scripting Runtime, we may use the following code; we access the output file in binary mode and we manually convert text to Unicode: 'the manual way Open pth For Binary Access Write As #1 Dim buffer() as Byte : buffer = "test text" Put #1, , buffer Close #1

Change the size of a shape in Powerpoint 2007 using VBA

Image
Automation in Powerpoint 2007 is not so easy as it seems, because the macro recording is not available any more. What I wanted to do is to change the shape of some graphs to have a specific size and location. The following code changes the size and location of the current shape according to our preferences. Public Sub ChangeImage() With ActiveWindow.Selection.ShapeRange(1) .LockAspectRatio = msoFalse .Width = 720 .Height = 153.9213 .Top = 77.8604 .Left = 0 ' optional '.ZOrder msoSendToBack End With End Sub Public Sub PrintInfo() Debug.Print vbCrLf & "Public Sub ChangeImage()" Debug.Print vbTab & "With ActiveWindow.Selection.ShapeRange(1)" With ActiveWindow.Selection.ShapeRange(1) Debug.Print vbTab & vbTab & ".LockAspectRatio = msoFalse" Debug.Print vbTab & vbTab & ".Width = " & Str(.Width) Debug.Print vbTab & vbTab & ".Heigh...

Get the current path in C#

Image
The most obvious way to retrieve the current application path is by using the following statement: currentPath = Application.StartupPath; That is the obvious solution but only when the project references the System.Windows.Forms library. To avoid referencing this library (in case it is not needed), the current directory may be retrieved in many ways. See below (alternative ways are commented): // Returns the current application path without a trailing '/'. It is the same with Application.StartupPath. private string GetCurrentPath() { ////returns the path with a trailing '/' //return System.AppDomain.CurrentDomain.BaseDirectory; ////retrieve the current path (without a trailing '/') //return Environment.CurrentDirectory; //return System.IO.Directory.GetCurrentDirectory(); return Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); }

Export modules using automation (VBA, Excel)

Image
Automation can really gives us the tools to do something very fast. The following code shows how to export all the modules in the current workbook to a destination folder. Public Sub ExportAll(targetPath as String) Dim xlApp As Excel.Application Dim xlWb As Excel.Workbook Dim VBComp As VBIDE.VBComponent ' Load workbook Set xlApp = Application 'xlApp.Visible = False Set xlWb = ActiveWorkbook 'xlApp.Workbooks.Open(sWorkbook) ' Loop through all files (components) in the workbook For Each VBComp In xlWb.VBProject.VBComponents ' Export the file If VBComp.Type = vbext_ct_StdModule Then _ VBComp.Export targetPath & VBComp.Name & ".bas" Next VBComp End Sub Two possible issues must be solved to correctly run this code. The first is to allow the code to access the VBA Object model programmatically. This can be done by correctly setting this from the Trust Center (from Excel Options). The second is to reference the Microsoft Visua...

Streamreader extensions (C#)

Image
OK. These two extension functions are very practical to me: omitting lines, and copying lines from one stream to another. Although it is very simple to implement it every time in code, I suggest using those extensions to be more productive! public static class StreamReaderExtensions { /// <summary> /// Jumps the number of lines that is specified. /// </summary> /// <param name="reader">The reader object.</param> /// <param name="count">The number of lines to jump.</param> public static void OmitLines(this StreamReader reader, int count) { for (int iLine = 0; iLine < count; iLine++) reader.ReadLine(); } public static void CopyLinesTo(this StreamReader source,StreamWriter target, int count) { for (int iLine = 0; iLine < count; iLine++) target.WriteLine(source.ReadLine()); } }

Calling Fortran intrinsic functions from Visual Basic

Image
There is a great way to call the Fortran intrinsic libraries from Visual Basic, without wrapping them to dynamic libraries. I have the Digital Fortran installed on my computer, so I found out one of the running DLLs which is the dforrt.dll and that contains the Fortran intrinsic libraries (which are used by the Digital compiler). I simply opened the DLL with the Depends program and I found out the name of the functions that are declared in the DLL file. Knowing that the tangent function is declared as DTAN in Fortran, I found out some functions and declared them in a Visual Basic module file like this: Public Declare Function DTAN# Lib "dforrt.dll" Alias "_FXDTAN" (x#) Public Declare Function DTAN5# Lib "dforrt.dll" Alias "_FXIDTAN" (x#) And here is a sample call: Const PI As Double = 3.14159265358979 'the tangent of PI/4 will return 1.0 Debug.Print DTAN(PI / 4) Of course the tangent function is an intrinsic one in Visual Basic. H...

Cross thread UI calls in C#

Image
If you try to call UI functions through threads other than the one the created the UI elements then an error will occur. To avoid those type of errors we need to have thread-safe calls to the corresponding Windows controls. For example, to make a thread-safe call for a textbox control, the following is valid: private void SetText(string text) { if (txtCommand.InvokeRequired) this.Invoke(new Action<string>(SetText), text); else txtCommand.Text = text; } The Invoke function will be called if the function is called from a thread other than the one that created the control. Here is a second example that will take two arguments; the first one is the control itself. private void EnableButton(Button button, bool enabled) { // InvokeRequired compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (button.InvokeRequired) button.Invoke(new Action<Button...