我正在尝试确定在我的VBA脚本中在单元格内计算3个值的最佳方法:
脚本中的当前格式:
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 & "Srv" & ","
logSTR = logSTR & "E-mail" & ","
logSTR = logSTR & "Env." & ","
logSTR = logSTR & "Protect" & ","
logSTR = logSTR & "DB" & ","
logSTR = logSTR & "# VMs" & ","
logSTR = logSTR & "Name" & ","
logSTR = logSTR & "Cluster" & ","
logSTR = logSTR & "VLAN" & ","
logSTR = logSTR & "NumCPU" & ","
logSTR = logSTR & "MemoryGB" & ","
logSTR = logSTR & "C" & ","
logSTR = logSTR & "D" & ","
logSTR = logSTR & "App" & ","
logSTR = logSTR & "TotalDisk" & ","
logSTR = logSTR & "Datastore" & ","
logSTR = logSTR & Chr(13)
logSTR = logSTR & BuildValuesString("C", "18,19,20,21,22")
logSTR = logSTR & BuildValuesString("C", "26,27,28,29,30,31,32,33")
logSTR = logSTR & Chr(13)
logSTR = logSTR & BuildValuesString("C", "18,19,20,21,22")
logSTR = logSTR & BuildValuesString("C", "37,38,39,40,41,42,43,44")
logSTR = logSTR & Chr(13)
logSTR = logSTR & BuildValuesString("C", "18,19,20,21,22")
logSTR = logSTR & BuildValuesString("C", "48,49,50,51,52,53,54,55")
Open "Z:\Requests(Test)\" & ThisWorkbook.Name & ".csv" For Append As #My_filenumber
Print #My_filenumber, logSTR
Close #My_filenumber
End Sub
此VBA脚本正在将Excel工作表单元格中的数据导出为CSV文件,我希望它还可以计算单元格“C”“32”或“C”“33”中存在的数字并放入“TotalDisk”标题下的CSV文件中的进程单元格。
值将是由列分隔的3个数字;例如:20,30,10。我想将这3个数字(在本例中为60)的结果放在下一个单元格中。
需要在C-32 OR C-33中进行计算的原因是数据只能填充其中一个。因此,我还需要为C-43或C-44和C-54或C-55细胞做同样的事情。
感谢您提供的任何信息
答案 0 :(得分:2)
'sum the comma-separated values in the first non-empty cell in rng
Function TotalIt(rng As Range)
Dim c, arr, t, rv As Double, v
For Each c In rng.Cells
If Len(c.Value) > 0 Then
arr = Split(c.Value, ",")
For Each v In arr
If IsNumeric(v) Then rv = rv + v
Next v
Exit For
End If
Next c
TotalIt = rv
End Function
'usage (add at the appropriate places in your code)
logSTR = logSTR & TotalIt(Range("C32:C33"))
BTW VBA有一个内置的String()
功能,与BuildNullStrings