VBA和连接函数

时间:2017-12-09 10:12:40

标签: excel vba concatenation formula

我实际上是想优化我用来配置一堆控制器(网络)的现有连接公式

我有Sheet1,我输入了从A2到E2所需的所有细节 我有Sheet2在哪里产生整体连接,包括来自Sheet1.A2的valude并包含一些命令,这里是连接公式:

= CONCATENATE(“ap”,Imported_Data!B2,CHAR(10),“ip enable”,CHAR(10),“ip mode static”,CHAR(10),“ip addr”,Imported_Data!A2,“ “,Imported_Data!L $ 2,”gateway“,Imported_Data!L $ 3,CHAR(10),”ip name-server“,Imported_Data!L $ 4,”“,Imported_Data!L $ 5,CHAR(10),”devname“, Imported_Data!C2,CHAR(10),“description”,CHAR(147),Imported_Data!D2,CHAR(147),CHAR(10),“location”,CHAR(147),Imported_Data!E2,CHAR(147), CHAR(10),“结束”)

以及结果如下:

"ap 00:00:00:00:00:00
 ip enable 
 ip mode static 
 ip addr 1.1.1.1 255.255.0.0 gateway 172.27.1.1
 ip name-server 4.2.2.1 4.2.2.2
 devname name
 description “Description“
 location “location“
 end"

为了让它在控制器上被接受是操纵结果,将连接结果复制到notepad ++中,删除从连接公式中添加的“”,并用“”替换CHAR(147)(仅限于方式我发现它有效)

我想在VBA中使用的是一个过滤器:

1)在连接块的开头和结尾删除“” 2)在描述和位置替换“with”“

最终结果应为:

ap 00:00:00:00:00:00
 ip enable 
 ip mode static 
 ip addr 1.1.1.1 255.255.0.0 gateway 172.27.1.1
 ip name-server 4.2.2.1 4.2.2.2
 devname name
 description "Description"
 location "location"
 end

任何建议/建议?

1 个答案:

答案 0 :(得分:0)

这是你应该检查它是否适合你的目的的一种方式。

首先编辑公式,将CHAR(147)替换为CHAR(34),如下所示:

=CONCATENATE("ap ",Imported_Data!B2,CHAR(10)," ip enable ",CHAR(10)," ip mode static ",CHAR(10)," ip addr ",Imported_Data!A2," ",Imported_Data!L$2," gateway ",Imported_Data!L$3,CHAR(10)," ip name-server ",Imported_Data!L$4," ",Imported_Data!L$5,CHAR(10)," devname ",Imported_Data!C2,CHAR(10)," description ",CHAR(34),Imported_Data!D2,CHAR(34),CHAR(10)," location ",CHAR(34),Imported_Data!E2,CHAR(34),CHAR(10)," end")

然后将下面的代码粘贴到VBE。确保更新单元格引用以适应。

Public Sub CopyConcatToNotepad()
    Dim objDataObj As Object
    Dim strFormula

    strFormula = Split(Sheets(2).Range("A1").Value, vbCrLf) 'Write correct cell reference for CONCATENATE formula cell!
    Dim strOut As String
    strOut = Join(strFormula, vbCrLf)

    'This is ClsID of MSFORMS Data Object
    Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    objDataObj.SetText strOut, 1
    objDataObj.PutInClipboard

    Set objDataObj = Nothing
End Sub

然后运行此代码以根据需要将文本复制到剪贴板。如果您将在Notepad ++中执行CTRL + V,那么它将给出所需的结果!

编辑:修改了合并要求的代码。

Public Sub CopyConcatToNotepadSelCells()
Dim objDataObj As Object
Dim rG As Range
Dim strFormula
Dim strOut As String

'Loop through all selected cells and build concat string
For Each rG In Selection
    strFormula = Split(rG.Value, vbCrLf)
    If Len(strOut) = 0 Then
        strOut = Join(strFormula, vbCrLf)
    Else
        strOut = strOut & vbCrLf & Join(strFormula, vbCrLf)
    End If
Next rG

'This is ClsID of MSFORMS Data Object
Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
objDataObj.SetText strOut, 1
objDataObj.PutInClipboard

Set objDataObj = Nothing
End Sub