简体   繁体   中英

Excel-VBA string manipulation issue

I am trying to copy some 8-digit numbers to use in a SQL search.

The SQL query gave me errors and after some debugging I found that the string doesn't contain all the data. It seems that after 25 or so numbers my for loop stops entering data as if the string is full.

Thanks for the help...

Lots = ""
For iRow = 2 To 500
    If IsEmpty(Sheets("Filtered Data").Cells(iRow, 2)) Then Exit For
    Lots = Lots & ",'" & Sheets("Filtered Data").Cells(iRow, 2).value & "'"
Next iRow

Lots = "(" & Mid(Lots, 2, Len(Lots) - 1) & ")"

Your code works fine. Presumably you have an empty cell in the column which is making it exit the loop....

you should post your data raising the errors

as for while you can consider the following code to build-up the string exploiting Join() function

Dim Lots As String

With Worksheets("Filtered Data") '<--| change "Filtered Data" with your actual worksheet name
    With .Range("B2", .Cells(.Rows.Count, 2).End(xlUp)) '<-- consider its column "B" cells from row 2 down to last non empty one
        Lots = "('" & Join(Application.Transpose(.Value), "','") & "')" '<-- build up the string
    End With
End With

this assumes that all non empty cells in column "B" are contiguous (ie non blank cells in between non blank ones), but it can be easily modified should this not be the case

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