|
|
Title | Use VBA code to add descriptions of the system's drives to a Word document |
Description | This example shows how to use VBA code to add descriptions of the system's drives to a Word document. |
Keywords | Word, Office, list drives, disk drives |
Categories | Office |
|
|
Note: Add a reference to Microsoft Scripting Runtime.
The DocumentDrives subroutine creates a FileSystemObject and loops through its Drives collection to see what drives are available.
For each drive, the code adds the drive's letter to the Word document and gives it the Heading 1 style.
If the drive is available, the code then displays information about it. It calls subroutine AddText to add the information to the Word document, set a tab at 2 inches in the text, and start a new paragraph.
If the drive is not available, the code displays question marks for most of the drive's values. (The code crashes if it tries to evaluate these values for a drive that is not ready.)
|
|
Public Sub DocumentDrives()
Dim fso As New FileSystemObject
Dim dr As Drive
On Error Resume Next
For Each dr In fso.Drives
Selection.TypeText "Drive " & dr.DriveLetter
If dr.IsReady Then
Selection.Style = _
ActiveDocument.Styles("Heading 1")
Selection.TypeParagraph
AddText "Status:" & vbTab & "Ready"
AddText "Drive Type:" & vbTab & dr.DriveType
AddText "Volume Name:" & vbTab & dr.VolumeName
AddText "Total Size:" & vbTab & _
FormatNumber(dr.TotalSize, 0) & " (" & _
FormatBytes(dr.TotalSize) & ")"
AddText "Available Space:" & vbTab & _
FormatNumber(dr.AvailableSpace, 0) & " (" & _
FormatBytes(dr.AvailableSpace) & ")"
AddText "Free Space:" & vbTab & _
FormatNumber(dr.FreeSpace, 0) & " (" & _
FormatBytes(dr.FreeSpace) & ")"
AddText "File System:" & vbTab & dr.FileSystem
AddText "Serial Number:" & vbTab & _
dr.SerialNumber
Else
Selection.Style = _
ActiveDocument.Styles("Heading 1")
Selection.TypeParagraph
AddText "Status:" & vbTab & "Not Ready"
AddText "Drive Type:" & vbTab & dr.DriveType
AddText "Volume Name:" & vbTab & "?"
AddText "Total Size:" & vbTab & "?"
AddText "Available Space:" & vbTab & "?"
AddText "Free Space:" & vbTab & "?"
AddText "File System:" & vbTab & "?"
AddText "Serial Number:" & vbTab & "?"
End If
Next dr
End Sub
Private Sub AddText(ByVal txt As String)
Selection.TypeText txt
Selection.ParagraphFormat.TabStops.Add _
Position:=InchesToPoints(2), _
Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
Selection.TypeParagraph
End Sub
|
|
Helper function FormatBytes returns a number in KB, GB, and so forth as in
44.7 GB. See the code for details.
|
|
|
|
|
|