通过VBA重新组织Excel值

时间:2014-12-17 04:42:16

标签: excel vba csv

我正在开发一个网络项目,我需要输出一个CSV文件以供数据库使用。我通过内部telnet上的WMIC命令拉出一个列表。它吐出一个excel列表,包括计算机主机名,接口名,IP和MAC地址。不幸的是,它们的格式不是最好的,我需要重新排列数据以生成CSV文件。我的输出列出了主机名和接口名称,然后列出了主机名和IP / MAC,如下所示。有些机器有比其他机器更多的接口,所以我不能倒计时并将其复制到新的单元格。

接口名称的顺序虽然与IP和mac匹配。输出基于索引,所以我只需要弄清楚如何合并线。我不确定我是否可以将它变成数组或什么。我的理想输出是主机名,接口名称,IP,MAC。我只是不确定如何重新排列数据。该计划将在VBA宏中包含将进行重组的代码。关于重新排列的最佳方法的任何建议?感谢

computer1,InterfaceName 1  
computer1,InterfaceName 2  
computer1,InterfaceName 3  
computer1,InterfaceName 4  
computer1,{"127.0.0.1"} 00:00:00:00:00:01  
computer1,{"127.0.0.2"} 00:00:00:00:00:02  
computer1,{"127.0.0.3"} 00:00:00:00:00:03  
computer1,{"127.0.0.4"} 00:00:00:00:00:04  
computer2,InterfaceName 1  
computer2,InterfaceName 2  
computer2,{"127.0.0.1"} 00:00:00:00:00:01   
computer2,{"127.0.0.2"} 00:00:00:00:00:02  

我希望得到这样的东西。

computer1,InterfaceName 1,127.0.0.1, 00:00:00:00:00:01
computer1,InterfaceName 2,127.0.0.2, 00:00:00:00:00:02
computer1,InterfaceName 3,127.0.0.3, 00:00:00:00:00:03
computer1,InterfaceName 4,127.0.0.4, 00:00:00:00:00:04
computer2,InterfaceName 1,127.0.0.1, 00:00:00:00:00:01
computer2,InterfaceName 2,127.0.0.2, 00:00:00:00:00:02

这是我最终想出来的。

'Gather last row
Dim iRow As Long
iRow = Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

'split column in two, A: Hostnames,Interface B:IP,Mac
Range("A1").Select
Dim test As Integer
For i = iRow To 1 Step -1
If InStr(Cells(i, 1), "{") Then
Cells(i, 2).Value = Cells(i, 1).Value
Cells(i, 1).ClearContents
End If
Next

Range("A1").Select

'delete blank spaces and move up
Range(Cells(1, 1), Cells(iRow, 2)).SpecialCells(xlCellTypeBlanks).Delete shift:=xlUp

Range("A1").Select
iRow = Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

'format B: Column
Dim iPos As Integer
Dim sValue As String
For i = iRow To 1 Step -1
sValue = ""
'remove Hostname and leave comma
iPos = InStr(Cells(i, 2), ",")
sValue = Mid(Cells(i, 2).Value, iPos)
'add command between IP and MAC
iPos = InStr(sValue, "}")
sValue = Left(sValue, iPos) & "," & Right(sValue, Len(sValue) - iPos)
'remove brackets and quotes
sValue = Replace(sValue, "{", "")
sValue = Replace(sValue, "}", "")
sValue = Replace(sValue, """", "")

'merge cells
Cells(i, 1).Value = Trim(Cells(i, 1).Value) & Trim(sValue)

'delete B: cell
Cells(i, 2).ClearContents
Next

1 个答案:

答案 0 :(得分:0)

如果您提供的示例数据代表实际数据,我将使用两步法。首先,我将数据拆分为两个单独的列表。所有主机名/接口名称的一个列表和主机名/ ip / mac的第二个列表。拆分可以像检测第二列是否以'{'开始一样轻松完成。

您应该获得如下列表:

<强>接口

computer1,InterfaceName 1  
computer1,InterfaceName 2  
computer1,InterfaceName 3  
computer1,InterfaceName 4
computer2,InterfaceName 1  
computer2,InterfaceName 2  

<强>地址

computer1,{"127.0.0.1"} 00:00:00:00:00:01  
computer1,{"127.0.0.2"} 00:00:00:00:00:02  
computer1,{"127.0.0.3"} 00:00:00:00:00:03  
computer1,{"127.0.0.4"} 00:00:00:00:00:04  
computer2,{"127.0.0.1"} 00:00:00:00:00:01   
computer2,{"127.0.0.2"} 00:00:00:00:00:02  

一旦你有了,你可以根据索引合并它们。它可能不是最有效的方式,但对我来说似乎是最简单的方法。