使用“分隔符”在VBA中补充更多单元格

时间:2014-03-04 13:38:11

标签: excel vba excel-vba hyperlink

我正在尝试使用VBA代码从GCmap.com生成地图。 我在一栏中有很长的机场对列表。生成地图的超链接格式为:

http://www.gcmap.com/map?P=”&(calue in .cell(1.51))&“%0d%0a”&(calue in .cell(2.51)& so so ...

'%0d%0a - 是一个需要介于值

之间的分隔符

问题是这个列表很长而且只做简单的循环会导致超长的超链接(有时候生成地图的时间太长)所以它必须是这样的 if valueOfFirstCell = ValueOfCellBellow然后 '跳到下一个

我试过这个(可能是最糟糕的代码,但请注意我只是VBA的初学者:)

Sub hyperlinkgenerator()

Dim separator As String  ' declared the 'separator' value
separator = "%0d%0a"
Dim datarow, irow As Integer
Dim myval as Range

With Sheets("Direct flights")

   Set myval = .Cells(datarow, 51)

   Do While myval <> ""     ' do until last empty row

Dim Value1 As String
Value1 = Sheets("Direct flights").Cells(datarow, 51) ' declare value of the first cell

Dim Value2 As String

Value2 = Sheets("Direct flights").Cells(datarow + 1, 51) ' declare value of cell bellow

If Value1 = Value2 Then

datarow = datarow + 1

Else: 'enter Value1 in hyperlink that is followed by & separator
'also the hyperlink must start with: http://www.gcmap.com/map?P=
' and end with %0d%0a&MS=wls&MR=540&MX=720x360&PM=* 

End If

datarow = datarow + 1

Loop

End With

End Sub

最终链接如下:

http://www.gcmap.com/map?P=LGW-AMS%0d%0aAMS-LHR%0d%0aLCY-AMS%0d%0aLUX-AMS%0d%0aBRE-AMS%0d%0aCWL-AMS%0d%0aNUE-AMS%0d%0aAMS-JFK%0d%0a&MS=wls&MR=540&MX=720x360&PM= *

我不知道如何保持循环向Hyperlink添加新文本和新文本。一旦用户点击按钮(这很容易),也应生成并打开超链接。

非常感谢提前!

1 个答案:

答案 0 :(得分:0)

尝试一下:

Sub hyperlinkgenerator()
    Dim thisVal As String
    Dim nextVal As String
    Dim currentRow As Long
    Dim hyperlink As String

    currentRow = 1 ' or whatever the first row is
    hyperlink = ""

    With Sheets("Direct flights")
        Do While True
            thisVal = .Cells(currentRow, 1).Value
            nextVal = .Cells(currentRow + 1, 1).Value

            If thisVal = "" Then
                Exit Do
            ElseIf thisVal <> nextVal Then
                hyperlink = hyperlink & thisVal & "%0d%0a"
            End If

            currentRow = currentRow + 1
        Loop

    End With

    hyperlink = "http://www.gcmap.com/map?P=" & hyperlink & "&MS=wls&MR=540&MX=720x360&PM="

    MsgBox hyperlink
End Sub