2017-11-10 79 views
0

我有一個包含PNEZD(點,北,東,海拔,描述)的點的大量列表,每個點都有幾個屬性。我如何將這些額外的屬性列組合到我的D列中,並用空格分隔?我可以按一下按鈕嗎?幾個點的VBA在Excel中格式化PNEZD字符串

例子是

10,1000,5000,50,tree,birch,12IN 

11,1100,5500,55,tree,spruce,10IN 

12,1130,5560,54,powerpole,tele,wood,12IN,guyed 

我想過去的幾年結合,從而將讀取:

10,1000,5000,50,tree birch 12IN 

11,1100,5500,55,tree spruce 10IN 

12,1130,5560,54,powerpole tele wood 12IN guyed 

請幫助!

回答

0

您可以在VBA中創建一個用戶定義的函數,然後您可以在工作表上使用它作爲任何常規公式。

從Excel中,按Alt + F11進入VBA編輯器。一旦出現,請按Ctrl + R顯示或激活Project Explorer。右鍵單擊模塊節點,然後選擇插入 - >模塊。將以下代碼放入模塊中:

Option Explicit 

Public Function GetPnezdLabel(pnezd As Variant) As Variant 
    On Error GoTo errHandler 

    Dim result As Variant 
    Dim parts As Variant 
    Dim lastPartIndex As Long 
    Dim intermediatePartIndex As Long 
    Dim index As Long 

    result = "" 

    parts = Split(CStr(pnezd), ",", Compare:=VbCompareMethod.vbBinaryCompare) 
    lastPartIndex = UBound(parts) 
    intermediatePartIndex = Application.WorksheetFunction.Min(3, lastPartIndex) 

    For index = 0 To intermediatePartIndex 
     result = result & parts(index) & IIf(index < lastPartIndex, ",", "") 
    Next 

    For index = 4 To lastPartIndex 
     result = result & parts(index) & IIf(index < lastPartIndex, " ", "") 
    Next 

Done: 
    GetPnezdLabel = result 
    Exit Function 

errHandler: 
    result = XlCVError.xlErrValue 
    Resume Done 
End Function 

按Alt + F11返回到Excel。現在,假設您在單元格A1中有一個PNEZD值,您可以在例如B1如下:

=GetPnezdLabel(A1) 

你會看到結果出現。

GetPnezdLabel函數背後的原理是以逗號分隔參數的值並從零件生成結果。

0

有關信息,可以通過以下公式獲得相同的結果。

假設你的數據是細胞A2然後在細胞D2插入下列公式和複製下來。

=TRIM(LEFT(SUBSTITUTE(A2,",",REPT(" ",199),4),199)) &","& SUBSTITUTE(TRIM(RIGHT(SUBSTITUTE(A2,",",REPT(" ",199),4),199)),","," ")

正如你指出VBA具體而言,你可能不希望一個公式解決方案。