简体   繁体   中英

How do you make an Excel spreadsheet range store a VBA variable?

Okay so I have spent.. I'll just say.. like an hour (sadly I am lying, its been like a whole week) trying to figure this out. And I can't figure it out godd*mnit >_<

Assume we have a text file in notepad ( _A_File_.txt ) containing just 4 lines:

ACCOUNT NUMBER: 123456789    '(line 2)
SHORT NAME: JON SMITH        '(line 2)
ACCOUNT NUMBER: 987654321    '(line 3)
SHORT NAME: BOB BARKER       '(line 4)

Let's assume that within an excel spreadsheet the below:

Range C1 = "actNumberTrim"
Range C2 = "shortNameTrim"
Range C3 = "actNumberTrim"
Range C4 = "shortNameTrim"

Lets also assume the below VBA script:

Sub obey_me_you_stoopit_code_()

Dim actNumber As Integer
Dim shortName As Integer
Dim actNumberTrim As String
Dim shortNameTrim As String
Dim trimArray1 As Variant
Dim myFile As String
Dim text As String
Dim textline As String


actNumber = InStr(text, "ACCOUNT NUMBER: ") 'THERE IS A SPACE BETWEEN : AND "
shortName = InStr(text, "SHORT NAME: ") 'THERE IS A SPACE BETWEEN : AND "
actNumberTrim = Mid(text, actNumber + 16, 10)
shortNameTrim = Mid(text, shortName + 12, 10)


myFile = "C:\Users\Bob\Desktop\_A_File_.txt"

Open myFile For Input As #1
Do Until EOF(1)

    Line Input #1, textline
    text = text & textline
    Loop

trimArray1 = ThisWorkbook.Worksheets("sheet1").Range("C1:C4")


For i = 1 To UBound(trimArray1)

 MsgBox trimArray1(i, 1)

Next i
Close #1
End Sub

the output I get is:

[ actNumberTrim ]
[ shortNameTrim ]
[ actNumberTrim ]
[ shortNameTrim ]

How would I go about fixing the above so that values in Ranges C1:C4 are treated as:

  1. Variables and not, say.. pointless text in a cell
  2. So that the output returned is:

     [ 123456789 ] [ JON SMITH ] [ 987654321 ] [ BOB BARKER ] 

I've tried changing the data types of actNumberTrim and shortNameTrim . It didn't work All I got was this:

Run-Time Error: "Your code sucks brah"

Thoughts?

EDIT 1 (Attempt using Microsoft Scripting Runtime)

    Dim trimArray1 As Variant
    Dim myFile1 As String
    Dim text As String
    Dim textline As String
    Dim myDict As New Dictionary

    myFile1 = "C:\Users\BOB\Desktop\_A_File_.txt"
    Open myFile1 For Input As #1
    Do Until EOF(1)

        Line Input #1, textline
        text = text & textline
        Loop
    Close #1
    trimArray1 = ThisWorkbook.Worksheets("sheet22").Range("C1:C4")
    v = Split(textline, ":") 'where v has been declared to be variant
    myDict.Add Trim(v(0)), Trim(v(1))
    For i = 1 To UBound(trimArray1)

    MsgBox myDict(trimArray1(i, 1))

    Next i


    [ BLANK ]
    [ BOB BARKER ]
    [ BLANK ]
    [ BOB BARKER ]

Cells C1:C4 Contained:

    ACCOUNT NUMBER
    SHORT NAME
    ACCOUNT NUMBER
    SHORT NAME

Not sure what I am doing wrong or if I have overlooked something. How would I use this method for fields that don't have ":" separating them? The version of the text file that I had posted was a little oversimplified. Feedback?

EDIT 2 Below was my original approach

Below is an example of two full records within an example text file:

    ACCOUNT ABCDEF12                                                                 
    CUSTOMER NAME:    JOHN B. SMITH         CSA REP:  154983                   
    ACCOUNT OPEN:     05/10/15
    CUSTOMER ADDRESS: 123 SOMEWHERE DRIVE   SOMETHING HERE:                   
    LAST ORDER:       06/24/2011             COUNTRY CODE: UNITED STATES      
    INVOICE #:        123456789             STATE CODE:    CALIFORNIA         
    LAST MAINTENANCE: 01/02/15               COUNTY CODE:  UNCODED            
    SOME INDICATOR:   NO   COMPLAINTS: NO   IPM IND:       DATAPREP/PERF4     
    SOME INDICATOR:   NO STATUS:  NONE      AUTO RENEW:    YES                
    SOMETHING HERE   NO                             
    SOMETHING HERE:          ABC IND:       
    SOMETHING HERE   2    ABC ASSET NO:  T                                           

    ACCOUNT ABCDEF12                                                                 
    CUSTOMER NAME:    JOHN B. SMITH         CSA REP:  154983                   
    ACCOUNT OPEN:     05/10/15
    CUSTOMER ADDRESS: 123 SOMEWHERE DRIVE   SOMETHING HERE:                   
    LAST ORDER:       06/24/2011             COUNTRY CODE: UNITED STATES      
    INVOICE #:        123456789             STATE CODE:    CALIFORNIA         
    LAST MAINTENANCE: 01/02/15               COUNTY CODE:  UNCODED            
    SOME INDICATOR:   NO   COMPLAINTS: NO   IPM IND:       DATAPREP/PERF4     
    SOME INDICATOR:   NO STATUS:  NONE      AUTO RENEW:    YES                
    SOMETHING HERE:   NO                             
    SOMETHING HERE:          ABC IND:       
    SOMETHING HERE:   2    ABC ASSET NO:  T                                               

Below was the way I had originally coded it:

'
    Dim myFile As String
    Dim text As String
    Dim textline As String
    Dim cstAct as integer
    Dim actOpe as integer
    Dim cusNam as integer
    Dim act as integer
    Dim reg as integer

    myFile = "put file patch to text file here"
    myFile = Application.GetOpenFilename()

    Do Until EOF(1)
    Line Input #1, textline
    text = text & textline
    Loop

    cusAct = InStr(text, "ACCOUNT ")
    actOpe = InStr(text, "ACCOUNT OPEN:")
    reg = InStr(text, "REGION:")
    cusNam = InStr(text, "CUSTOMER NAME:")

    For i = 2 To ThisWorkbook.Worksheets("b2").Range("a65536").End(xlUp).Row
    ThisWorkbook.Worksheets("name").Range("a" & i).Value = Mid(text, act + 6, 9)
    ThisWorkbook.Worksheets("name").Range("b" & i).Value = Mid(text, cstAct + 6, 9)
    ThisWorkbook.Worksheets("name").Range("c" & i).Value = Mid(text, actOpe + 13, 27)
    ThisWorkbook.Worksheets("name").Range("d" & i).Value = Mid(text, cusNam  + 20, 19)

    next i

    'Format and autofit                         
    For x = 2 To ThisWorkbook.Worksheets("b2").Range("a65536").End(xlUp).Row
    Range("a" & x).Value = Application.WorksheetFunction.Clean(trim(Range("a" & x)))
    Range("b" & x).Value = Application.WorksheetFunction.Clean(trim(Range("b" & x)))
    Range("c" & x).Value = Application.WorksheetFunction.Clean(trim(Range("c" & x)))
    'etc etc
    next x

You can use strings as keys to a dictionary (which act sort of like variables which are linked to the corresponding values ). In the VBA editor under Tools/References, include a reference to Microsoft Scripting Runtime . Then at the top of your code have a line like

Dim myDict As New Dictionary 

Then, when you loop through the file and load up the variable textline by the successive lines, don't tack it onto the end of a big variable but instead have the lines

v = Split(textline, ":") 'where v has been declared to be variant
myDict.Add Trim(v(0)), Trim(v(1))

Fix the cells in column C so that they coincide with the actual (trimmed) strings in the text file before the colon. No need to eliminate spaces - "Account Number" is a perfectly valid cell value and a perfectly valid dictionary key. Later, when you are looping through the values drawn from column C, replace

MsgBox trimArray1(i, 1)

By

MsgBox myDict(trimArray1(i, 1))

This should (if I understand your intentions correctly) do what you want it to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM