用可变来源替换vba

时间:2017-09-21 12:46:20

标签: excel vba excel-vba

必须使用特定的新链接替换超过800个长html代码中的多个不同链接。 得到一张Excel表格,其中包含A列中的旧链接和B列中的新链接。 我的目的是创建一个带有输入字段和输出字段的用户表单。我的目标是一个宏,用特定的新链接替换每个旧链接。我可以用一个链接来做,但不能用大约350个不同的链接列表。 我得到了

Private Sub CommandButton1_Click()
Dim varInput As String
Dim varOutput As String
varInput = tbInput
varOutput = Replace(varInput, "oldLink.intern/a1b2c3", "newLink.intern/z9y8x7")
tbOutput = varOutput
End

其中'tbInput'是我的第一个文本框,'tbOutput'是我的第二个,但不能用我的链接列表

2 个答案:

答案 0 :(得分:0)

使用ComboBox将为您提供AutoComplete的优势。

enter image description here

Option Explicit
Const OLDLINK_ROOT As String = "oldLink.intern/"
Const NEWLINK_ROOT As String = "newLink.intern/"

Private Sub cboOldLink_Change()
    With cboOldLink
        If .ListIndex = -1 Then
            txtNewLink.Value = ""
        Else
            txtNewLink.Value = NEWLINK_ROOT & .list(.ListIndex, 1)
        End If
    End With
End Sub

Private Sub UserForm_Initialize()
    Dim Column1Max As Long, Column2Max As Long, NewListWidth As Long
    With cboOldLink
        .ColumnCount = 2
        .list = getLinkList(Column1Max, Column2Max)
        .ColumnWidths = (Column1Max * .Font.Size + 1) & " pt;" & (Column2Max * .Font.Size + 1) & " pt;"
        NewListWidth = (Column1Max * .Font.Size + 1) + (Column2Max * .Font.Size + 1)
        If NewListWidth > .ListWidth Then .ListWidth = NewListWidth
    End With
End Sub

Function getLinkList(ByRef Column1Max As Long, ByRef Column2Max As Long) As Variant
    Dim cell As Range
    Dim olist As Object
    Dim key As String, item As String
    Dim list As Variant
    Dim x As Long
    Set olist = CreateObject("System.Collections.SortedList")
    With Worksheets("Sheet1")
        For Each cell In .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
            key = Right(cell.Value, Len(cell.Value) - Len(OLDLINK_ROOT))
            item = Right(cell.Offset(0, 1).Value, Len(cell.Offset(0, 1).Value) - Len(OLDLINK_ROOT))

            If Not olist.Contains(key) Then olist.Add key, item
        Next
    End With
    ReDim list(0 To olist.Count - 1, 0 To 1)

    For x = 0 To olist.Count - 1
        list(x, 0) = olist.GetKey(x)
        list(x, 1) = olist.GetByIndex(x)

        If Len(olist.GetKey(x)) > Column1Max Then Column1Max = Len(olist.GetKey(x))
        If Len(olist.GetByIndex(x)) > Column2Max Then Column2Max = Len(olist.GetByIndex(x))
    Next

    getLinkList = list
End Function

答案 1 :(得分:0)

好的,就这么简单:

Private Sub cbMach_Click()
Dim varIn As String
Dim varOut As String
Dim i As Integer
varIn = tbIn
For i = 1 To 500
    tbIn = Replace(tbIn, Cells(i, 1), Cells(i, 2))
Next
tbOut = tbIn
End Sub

太盲目了。谢谢你们!