weskpga
weskpga

Reputation: 2087

How do I replace strings with ID's using VBA?

I searched for an answer to this question, but it seems like the only ways that people have answered it are using Excel functions. I have a file in Excel that I load in to a text file, but new data comes out every week. I need to replace the Market names in this first column with their respective tickers, which are in this separate worksheet, but in the same Excel file.

For example, I want all 'CANADIAN DOLLAR - CHICAGO MERCANTILE EXCHANGE' cells to be replaced with 'CAD', all 'SWISS FRANC - CHICAGO MERCANTILE EXCHANGE' cells to be replaced with 'SWF', etc.

I would prefer if the names remained the same in the Excel file and were only changed when I transferred them to the text file. However, that's not essential if it's harder to do.

For reference, here's the code I'm using to write to the text file:

Sub getData1()
On Error GoTo ErrHandler:
''Finding Row Information
Dim Ticker As String
Dim rCount As Integer, i As Integer, j As Integer, rcCount As Integer, rowStr As String
rCount = Application.CountA([RDRows])
rcCount = Application.CountA([RDCols])
Myfile = "H:\wkoorbusch\Desktop\" & "CFTC_Fin_Data.txt"

Dim fnum As Integer
fnum = FreeFile
Open Myfile For Output As fnum
For i = 1 To rCount
    For j = 1 To rcCount
        rowStr = [Start].Offset(i, 0).Value & "," & [Start].Offset(0, j).Value _
        & "," & Format([Start].Offset(i, 2).Value, _
        "mm/dd/yyyy") & "," & [Start].Offset(i, j).Value
        Print #fnum, rowStr
    Next j
Next i
Close fnum
Exit Sub

ErrHandler:
    Close fnum
End Sub

Thanks in advance for any and all help.

Upvotes: 0

Views: 299

Answers (1)

SeanC
SeanC

Reputation: 15923

Place the Text and its replacement in 2 colums of your spreadsheet, then use

On Error Resume Next
Application.WorksheetFunction.VLookup(MyText,range("Sheet1!A1:B300"),2,False)
If Err.Number=1004 then msgbox "Value " & MyText & " not found"

to return the replacement text. A trappable err.Number of 1004 is returned when the lookup value is not found.

(functionally equivalent to VLOOKUP as a spreadsheet formula)

Upvotes: 1

Related Questions