【发布时间】:2016-12-01 16:34:20
【问题描述】:
我正在使用 VBA 脚本将 Excel 文档中的数据编译为 CSV 文件,以便与 PowerCLI 脚本一起使用。我遇到了与列名中有额外空格相关的问题,我想确定一种方法:
引入一个函数来消除我的主 VBA 脚本中的多余空格,或者让与删除多余空格相关的 VBA TrimEText 部分与主 VBA 脚本同时运行
“主”VBA 脚本是:
Function BuildValuesString(colIndex As String, rows As String) As String
Dim val As Variant
For Each val In Split(rows, ",")
If Cells(val, colIndex) <> "" Then BuildValuesString = BuildValuesString & Cells(val, colIndex).Value & " , "
Next val
End Function
Function BuildNullStrings(numNullStrings As Long) As String
Dim iNullStrings As Long
For iNullStrings = 1 To numNullStrings
BuildNullStrings = BuildNullStrings & "" & " , "
Next iNullStrings
End Function
Sub WriteCSVFile2()
Dim My_filenumber As Integer
Dim logSTR As String
My_filenumber = FreeFile
logSTR = logSTR & "Name" & " , "
logSTR = logSTR & "VLAN" & " , "
logSTR = logSTR & "NumCPU" & " , "
logSTR = logSTR & "MemoryGB" & " , "
logSTR = logSTR & "C" & " , "
logSTR = logSTR & "D" & " , "
logSTR = logSTR & "App" & " , "
logSTR = logSTR & Chr(13)
logSTR = logSTR & BuildValuesString("C", "18,19,20,21,22")
logSTR = logSTR & BuildNullStrings(1)
logSTR = logSTR & BuildValuesString("C", "26,27,28,29,30,31,32")
logSTR = logSTR & Chr(13)
logSTR = logSTR & BuildNullStrings(6)
logSTR = logSTR & BuildValuesString("C", "36,37,38,39,40,41,42")
logSTR = logSTR & Chr(13)
logSTR = logSTR & BuildNullStrings(6)
logSTR = logSTR & BuildValuesString("C", "46,47,48,49,50,51,52")
Open "Z:\Operational Env. Requests\2016\Requests(Test)\" & ThisWorkbook.Name & ".csv" For Append As #My_filenumber
Print #My_filenumber, logSTR
Close #My_filenumber
End Sub
删除多余空格的部分是:
Sub TrimEText()
' This module will trim extra spaces from BOTH SIDES and excessive spaces from inside the text.
Dim MyCell As Range
On Error Resume Next
Selection.Cells.SpecialCells(xlCellTypeConstants, 23).Select
For Each MyCell In Selection.Cells
MyCell.Value = Application.WorksheetFunction.Substitute(Trim(MyCell.Value), " ", " ")
MyCell.Value = Application.WorksheetFunction.Substitute(Trim(MyCell.Value), "", " ")
MyCell.Value = Application.WorksheetFunction.Substitute(Trim(MyCell.Value), "", " ")
MyCell.Value = Application.WorksheetFunction.Substitute(Trim(MyCell.Value), "", " ")
MyCell.Value = Application.WorksheetFunction.Substitute(Trim(MyCell.Value), "", " ")
Next
On Error GoTo 0
End Sub
有没有一种方法可以同时运行而不需要在导出的 CSV 文档中选择单元格?就像在 VBA 脚本中指定 CSV 文档本身的单元格一样?
【问题讨论】:
-
是的 - 不要使用
Selection。查看this thread on avoiding the use of.Select。因此,只需设置一个您知道将包含数据的范围(查找最后一行可以帮助将其缩减到使用的范围),然后在其上运行宏。 -
另外,尽量避免使用
On Error Resume Next,它只是掩盖错误而不是处理它们 -
使用保存为 CSV 的临时工作表或与文本驱动程序的 ADODB 连接,这将变得非常容易且不易出错。