0

函数生成()

Dim varLookup As Collection
Dim sheetOutput As Worksheet
Dim sheetVariables As Worksheet
Dim intRow As Integer
Dim intCol As Integer

intRow = 1
intCol = 1

Set sheetVariables = Worksheets("variables")

Dim rngCountries As Range
Set rngCountries = sheetVariables.Range("A2:A250")

Dim rngCities As Range
Set rngCities = sheetVariables.Range("D1:D4195")

Dim rngAirports As Range
Set rngAirports = sheetVariables.Range("C1:C4195")

Set varLookup = New Collection
varLookup.Add "A1:A10", "[country]"

Dim countryList(1) As String
countryList(0) = "US"
countryList(1) = "FR"

Dim strOuput As String
strOutput = "From UK to "

Dim strCombo As String
strCombo = "From UK to [Country]"

'For every country in list
Set sheetOutput = Worksheets("keyphrases")
For Each c In rngCountries.Cells
    strOutput = "From UK to " & c.Value
    sheetOutput.Cells(intRow, intCol).Value = strOutput
    intRow = intRow + 1
Next
For Each c In rngCountries.Cells
    strOutput = "From " & c.Value & " to UK"
    sheetOutput.Cells(intRow, intCol).Value = strOutput
    intRow = intRow + 1
Next

'For every city in list
For Each c In rngCities.Cells
    strOutput = "From UK to " & c.Value
    sheetOutput.Cells(intRow, intCol).Value = strOutput
    intRow = intRow + 1
Next
For Each c In rngCities.Cells
    strOutput = "From " & c.Value & " to UK"
    sheetOutput.Cells(intRow, intCol).Value = strOutput
    intRow = intRow + 1
Next

'For every airport in list
For Each c In rngAirports.Cells
    strOutput = "From UK to " & c.Value
    sheetOutput.Cells(intRow, intCol).Value = strOutput
    intRow = intRow + 1
Next
For Each c In rngAirports.Cells
    strOutput = "From " & c.Value & " to UK"
    sheetOutput.Cells(intRow, intCol).Value = strOutput
    intRow = intRow + 1
Next
' From every City to Country [UK]
For Each c In rngCities.Cells
    strOutput = "From " & c.Value & " to UK"
    sheetOutput.Cells(intRow, intCol).Value = strOutput
    intRow = intRow + 1
Next

For x = LBound(countryList) To UBound(countryList) 'define start and end of array
    strOutput = "From UK to " & countryList(x)
Next x ' Loop!

Set sheetOutput = Nothing

结束功能

所以我有那个 2 公里长的代码,我还有大约 15 种其他组合要做。我怎样才能让它更容易?我不想复制和粘贴其他 15 种组合。

非常感谢

4

1 回答 1

3

编写一个传递范围的子程序,如下所示:

Sub PrintRange (r As Range)
    'For every city in list
    For Each c In r.Cells
        strOutput = "From UK to " & c.Value
        sheetOutput.Cells(intRow, intCol).Value = strOutput
        intRow = intRow + 1
    Next
    For Each c In r.Cells
        strOutput = "From " & c.Value & " to UK"
        sheetOutput.Cells(intRow, intCol).Value = strOutput
        intRow = intRow + 1
    Next
End Sub

然后你会调用如下:

PrintRange rngCities

为避免对范围进行硬编码,您可以使用命名范围。

于 2013-08-18T14:31:58.033 回答