如何编写在csv文件中编号不同行或字符串的vbscript?

时间:2015-03-22 05:00:45

标签: csv vbscript

我需要使用vbscript复制在Excel中完成的工作,但是我很难学习vbscript,请帮助。 vbscript需要打开并读取csv文件中的数据,然后读取column1中的数据,将每个不同(唯一)字符串编号为column2,任何重复或重复的字符串应具有相同的编号。 应该是什么结果的示例:

column1: A B C C D E B F E A G, column2:  1 2 3 3 4 5 2 6 5 1 7

以下是我到目前为止所做的...操作的逻辑不是很多,因为它已经有错误了。任何帮助将不胜感激。

Option Explicit
Dim objFSO, strInput, objInput
Dim arrValues, strItem, strLine
Dim strOutput, objOutput

Const ForReading = 1, ForWriting = 2

strInput = "sample.csv"
strOutput = "New"

Set objShell = CreateObject("WScript.Shell")
' Open the input file for read access
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInput = objFSO.OpenTextFile_(strInput, ForReading)

' Open the output file for writing.
Set objOutput = objFSO.OpenTextFile(strOutput, ForWriting)

' Read the file.
Do Until objInput.AtEndOfStream
strLine = objInput.ReadLine
' Skip blank lines.
If (Trim(strLine) <> "") Then
' Parse the fields in the file.
arrValues = CSVParse(strLine)
' Write the value in the first field to the output file.
objOutput.WriteLine arrValues(0)
End If
Loop

' Clean up.
objInput.Close
objOutput.Close

2 个答案:

答案 0 :(得分:0)

VBScript中用于分类任务的正确工具是Dictionary。演示:

>> Set d = CreateObject("Scripting.Dictionary")
>> aC1 = Split("A B C C D E B F E A G")
>> For Each c In aC1
>>     If Not d.Exists(c) Then
>>        d(c) = 1 + d.Count
>>     End If
>>     WScript.Echo c, d(c)
>> Next
>>
A 1
B 2
C 3
C 3
D 4
E 5
B 2
F 6
E 5
A 1
G 7

答案 1 :(得分:0)

记录excel宏录制器中的步骤。你必须重写一下,因为它使用了一种vbs没有的语法。

这适用于(我在vba中没有中篇9)xlRangeAutoFormatAccounting4

Selection.AutoFormat Format:=xlRangeAutoFormatAccounting4, Number:=True, _
    Font:=True, Alignment:=True, Border:=True, Pattern:=True, Width:=True

首先在vba的对象浏览器中查找常量。 xlRangeAutoFormatAccounting4 = 17

然后在对象浏览器中查看该函数,并查看函数定义的底部。

Function AutoFormat([Format As XlRangeAutoFormat = xlRangeAutoFormatClassic1], [Number], [Font], [Alignment], [Border], [Pattern], [Width])

所以vba变成vbs(和vbs在vba中工作)(正如你所看到的,你可以通过正确的方式计算出来,而不需要通常查看函数)

Selection.AutoFormat 17, True, True, True,True, True, True

所以你的代码变成了

objXLWs.Range("A3").CurrentRegion.Select.AutoFormat 17, True, True, True,True, True, True

您正在使用Excel,您可以将其记录在Excel中并让Excel编写您的代码。

Alt + T,M,R

然后是Home键,然后是Up Arrow。停止录音。

看看Excel写的是什么

Selection.End(xlUp).Select

或者您是否有录制的“转到”对话框

Application.Goto参考:=“R1C1” 或者如果您有录制的Ctrl + Home

范围( “A1”)。选择