0

I am running into a problem, Although very simple but stuck up, I have a string from a cell, I split the string into characters using Mid function and store it into an array. Now I want to print the array to a different range but I am unable to do it. I've tried many different codes but all in vein. please help.

My Code is as

Option Base 1
Function Takseer(Rg As Variant)
    Dim NewArray() As Variant
    Dim StrEx As String
    Dim k, l, m  As Integer
    StrEx = Rg
    StrEx = WorksheetFunction.Substitute(StrEx, " ", "")
    m = Len(StrEx)
    For k = 1 To m
        ReDim Preserve NewArray(1 To m)
            NewArray(k) = Mid(StrEx, k, 1)
    Next k
    Range("C1:C12") = NewArray

End Function
Imran Gee
  • 1
  • 3
  • What does your code do? What's wrong with it? – nicomp May 15 '21 at 11:06
  • In fact Its a lengthy program I want to split a string then store it in an array then paste array to sheet, After than get the array and perform calculations then again display it on screen and so on. So far it is not printing back – Imran Gee May 15 '21 at 11:14
  • Array holds the values as coded when printed into immediate window but so far unable to print the values to excel – Imran Gee May 15 '21 at 11:18

3 Answers3

0

Assuming the array you obtain is "Apple", "Orange", "Grape", "Durian", in order to write into worksheet you cannot directly call the variant. One way to write the value is to first get the length of your variant, then write the value from array starting from index 0, here is how I perform you expectation:

    Sub test1()

    Dim NewArray() As Variant
    Dim i As Long, arrayLoop As Long
    Dim StrEx As String
    Dim k, l, m  As Integer
    
    StrEx = "Hello today is my first day"
    StrEx = WorksheetFunction.Substitute(StrEx, " ", "")
    m = Len(StrEx)
    
    For k = 0 To m - 1
       ReDim Preserve NewArray(m - 1)
            NewArray(k) = Mid(StrEx, k + 1, 1)
    Next k

    
    i = UBound(NewArray) - LBound(NewArray) + 1

    For arrayLoop = 0 To i - 1
        Sheet1.Range("A" & arrayLoop + 1).Value = NewArray(arrayLoop)
    Next

End Sub

Please take note when perform array loop, you have to minus the length by 1, else it will be out of range, the reason is that array index always start from zero based (0)

And check the post for how to obtain length of array Get length of array?

Kin Siang
  • 2,644
  • 2
  • 4
  • 8
  • Still Unable to get the output – Imran Gee May 15 '21 at 11:40
  • Add breakpoint on your code before copy value to excel, add right-click on your newarrayK and add to watchlist to check whether it is properly stored as array. I am afraid your newArray is empty for some reason – Kin Siang May 15 '21 at 11:45
  • Yes did so, Array stores the value, Even displays it in immediate window – Imran Gee May 15 '21 at 11:58
  • I have amend my original code for you, if you still cannot work, no way I can help you solve your problem, thank you. – Kin Siang May 15 '21 at 12:17
0

You have to transpose the array to put values in a column.

Option Explicit
Option Base 1

Sub test()
   Call Takseer("ABCDEFGHUIJKL")
End Sub

Function Takseer(StrEx As String)

    Dim NewArray() As Variant, s As String, m As Integer, k As Integer
    s = Replace(StrEx, " ", "")
    m = Len(s)
    If m = 0 Then Exit Function
    ReDim NewArray(m)
    For k = 1 To m
        NewArray(k) = Mid(s, k, 1)
    Next k
    ' in a row
    Sheet1.Range("C1").Resize(1, m) = NewArray
    ' in a column
    Sheet1.Range("C2").Resize(m, 1) = WorksheetFunction.Transpose(NewArray)

End Function
CDP1802
  • 13,871
  • 2
  • 7
  • 17
  • Every thing works fine but still doesn't print to given range – Imran Gee May 15 '21 at 11:57
  • Pardon I couldn't get you – Imran Gee May 15 '21 at 12:04
  • @Imran Is the Function in a Workbook, Worksheet or Module ? How are you calling the function ? Is the Function in the same Workbook as the range you want to print to ? Range() without a sheet reference will print to the Activesheet. – CDP1802 May 15 '21 at 12:07
  • This function is in module, Yes you are right without sheet reference it should print it to active sheet. but I am unable to get it done – Imran Gee May 15 '21 at 12:12
  • Thank you so much. It worked but with a constant string. Unable to work it through with a cell reference. Please help – Imran Gee May 16 '21 at 11:34
  • @Imran Are you trying to use this as a User Defined Function in a spreadsheet cell ? – CDP1802 May 16 '21 at 11:38
  • Yes, I want it to be a UDF – Imran Gee May 16 '21 at 14:03
  • @Imran That was an important detail missing from your question. How did it work with a constant string, what did you enter on the spreadsheet ? – CDP1802 May 16 '21 at 14:33
  • I run it through Command Button assigned to Macro, entering details in cell a1, after modifying the sub to get value from referred cell. – Imran Gee May 16 '21 at 14:42
  • @Imran UDF's can't (easily) [change other cells](https://stackoverflow.com/questions/23433096/using-a-udf-in-excel-to-update-the-worksheet). Why not just use a formula like `=MID(SUBSTITUTE($A$1," ",""),ROW(),1)` in the range C1:C12. – CDP1802 May 16 '21 at 14:58
0

Some problems with your function:

  • A formula returns a value. It is not used to alter other properties/cells of a worksheet.
    • Hence you should set your results to the function; not try to write to a range
  • Dim k, l, m As Integer only declares m as Integer, k and l are unspecified so they will be declared as a variant.
  • The constructed array will be horizontal. If you want the results vertical, you need to Transpose it, or create a 2D array initially.
  • Option Base 1 is unnecessary since you explicitly declare the lower bound

Assuming you want to use this function on a worksheet, TestIt sets things up.

Note2: The formula on the worksheet assumes you have Excel with dynamic arrays. If you have an earlier version of Excel, you will need to have a different worksheet formula

See your modifed function and TestIt:

Modified with Transpose added to worksheet formula

Option Explicit
Function Takseer(Rg As Variant)
    Dim NewArray() As Variant
    Dim StrEx As String
    Dim k As Long, l As Long, m  As Long
    StrEx = Rg
    StrEx = WorksheetFunction.Substitute(StrEx, " ", "")
    m = Len(StrEx)
    For k = 1 To m
        ReDim Preserve NewArray(1 To m)
            NewArray(k) = Mid(StrEx, k, 1)
    Next k
    Takseer = NewArray

End Function

Sub TestIt()
    [a1] = "abcdefg"
    [c1].EntireColumn.Clear
    [c1].Formula2 = "=Transpose(Takseer(A1))"
End Sub

Modified to create 2d vertical array can't really use redim preserve on this array. And I prefer to avoid it anyway because of the overhead

Option Explicit
Function Takseer(Rg As Variant)
    Dim NewArray() As Variant, col As Collection
    Dim StrEx As String
    Dim k As Long, l As Long, m  As Long
    StrEx = Rg
    StrEx = WorksheetFunction.Substitute(StrEx, " ", "")
    m = Len(StrEx)
    
    Set col = New Collection
    For k = 1 To m
        col.Add Mid(StrEx, k, 1)
    Next k
    
    ReDim NewArray(1 To col.Count, 1 To 1)
    For k = 1 To col.Count
        NewArray(k, 1) = col(k)
    Next k
    
    Takseer = NewArray

End Function

Sub TestIt()
    [a1] = "abcdefg"
    [c1].EntireColumn.Clear
    [c1].Formula2 = "=Takseer(A1)"
End Sub

enter image description here

Note:

  • TestIt is merely to test the function. You should enter the appropriate formula yourself, either manually or programmatically, into the destination range.
  • If you do not have dynamic arrays, then you would need to enter an array formula into the destination range; or a formula using the INDEX function to return each element of the array.
  • In TestIt, you might change the line that puts the formula onto the worksheet to Range(Cells(1, 3), Cells(Len([a1]), 3)).FormulaArray = "=Takseer(a1)", but, again, it is anticipated that you would be entering the correct formula onto your worksheet manually or programmatically anyway.
Ron Rosenfeld
  • 53,870
  • 7
  • 28
  • 60
  • I am grateful for your help. I am getting error Object doesn't support this property or method. – Imran Gee May 15 '21 at 12:35
  • @ImranGee I cannot see your screen. Without knowing which code version you are using, nor which line the error refers to, I have no idea how to help. Clearly, from the screenshot, both versions work here. – Ron Rosenfeld May 15 '21 at 12:39
  • @ImranGee I am making a guess that your error occurs in the `Sub` and not in the `Function`. If that is the case, it probably has to do with the `Formula2` property. And if that is the case, you probably don't have dynamic arrays. Please re-read my ***Note 2*** and also my final, just added **Note** at the bottom of my answer. Also read Microsoft Help for your Excel version to understand about Array formulas. – Ron Rosenfeld May 15 '21 at 12:58
  • Thank you so much, now it runs properly. But when I do it manually it only prints first letter – Imran Gee May 15 '21 at 13:05
  • Yes exactly the error was in sub not in function. – Imran Gee May 15 '21 at 13:06
  • I have Excel 2007. How to enable dynamic Array or I have to upgrade my Excel – Imran Gee May 15 '21 at 13:07
  • @ImranGee *when I do it manually it only prints first letter*. Again, I am only guessing since you don't share exactly what you did or what you expect, and I cannot see your screen. I assume you are not properly entering the formula as an array formula in the manner the macro enters it, or in an alternative method using `INDEX`. I refer you back to my comment above: ***read Microsoft Help for your Excel version to understand about Array formulas*** – Ron Rosenfeld May 15 '21 at 13:14
  • @ImranGee I am unaware of any method to add dynamic arrays to Excel 2007, but we got along without them for years, and I wouldn't bother to upgrade for that reason alone. That said, there are many new and useful functions and methods in Office 365. – Ron Rosenfeld May 15 '21 at 13:15