Troubleshooting
Problem
I have a data file in which variable names are of varying length. I would like to truncate variable names to a specified number of characters such as 8. In my dataset, for each given variable, the first 8 characters are unique. How can I do so?
Resolving The Problem
The following script should assist you. Highlight the script below and click Edit->Copy. Next, click File->New->Script. Click Cancel. Delete any visible text. Click Edit->Paste. Next, click File->Save As and save the script using a name such as, 'TruncateVariableNames.sbs'. Exit the script window.
Next, run the DATA LIST syntax to generate sample data. The variables, 'workinghours,' 'jobfunction,' 'hourspent,' 'workingdays,' and 'vacationdays' will be created.
*Sample Data*.
DATA LIST free/ workinghours jobfunction hourspent workingdays vacationdays.
BEGIN DATA
END DATA.
LIST.
In the SPSS Data Editor, click Utilities->Run Script. Locate the saved script. Click Run. In this example, you should notice the variable names of your SPSS file are all truncated to the first 8 characters.
Read through the script on how to modify it to suit your own criteria for renaming variables to your specified number of characters.
Note that because the script makes use of the RENAME command, it will not execute if the specified number of characters for variable names results in duplicate variable names.
'___________________________________________________
'Begin Description
'This script will rename all variables
'of the currently open SPSS data file
'to a specified number of characters
'such as 8
'End Description
Sub Main
Dim i As Long
Dim strCommands As String
Dim strVariableList As String
Set objInfo = objSpssApp.SpssInfo
Set objData = objSpssApp.Documents.GetDataDoc(0)
For i = objInfo.NumVariables - 1 To 0 Step -1
strVariableList = strVariableList & vbCrLf _
& " " & (objInfo.VariableAt(i))
Dim strVars As String
'Here we specify the length of the variable names such as 8
'Replace the 8 with your specified number of characters
'Note that if the specified number of characters results
'in duplicate variable names, the script will not execute
strVars = strVars & " " & Left$(objInfo.VariableAt(i), 8)
Next
strCommands="RENAME VARIABLES(" & strVariableList & "="& strVars & ")" & "." & _
vbCrLf & "EXECUTE."
objSpssApp.ExecuteCommands strCommands, False
End Su
Related Information
Historical Number
41272
Was this topic helpful?
Document Information
More support for:
IBM SPSS Statistics
Software version:
Not Applicable
Operating system(s):
Windows
Document number:
155301
Modified date:
16 April 2020
UID
swg21475211