Copying a string, which is all numerical digits - excel

Am going crazy trying to just copy and paste in Excel.
I have a worksheet that I am exporting, from AutoCAD if it matters, and then trying to copy and paste a section of it onto another sheet. One of the columns has a four-digit number, starting with 0, that I would like to keep as a string. (I think AutoCAD is exporting it as a string, and expects it back as a string for importing, which explains why I do not want any workaround where the string TYPE is lost)
When I do the copy/paste "manually" with CTRL+C and CTRL+V, the columns paste fine (e.g., "0101" pastes as "0101" although the top left corner of the cells are greened with a message that says "the number in the cell is formatted as text". I'm thinking: no, it's a string, just leave it alone, please! And it does leave it alone, there.
However, my VBA script to do the same seems to lose the TYPE of the value when pasting (e.g., "0101" becomes 101, and there are no green corners with comments). I have verified this with the manual TYPE function under the Formulas bar.
Here is my script:
ThisWorkbook.Worksheets("Sheet1").Range("B" & numTemplateHeaderRows + 1 & ":Y" & numImportRows + 1).Value = _
wsImport.Range("B" & numTemplateHeaderRows + 1 & ":Y" & numImportRows + 1).Value
I've even tried to Dim an array, put the values in there, and then iterate through the problematic column with Cstr. Still, when I set the values on the receiving sheet, those Strings become numbers.
Does anyone know what might be causing Excel to do this conversion? Can I turn it off, please?

If you want to copy-paste a cell or range, use PasteSpecial:
Sub copyRange(wsImport As Worksheet, numTemplateHeaderRows As Integer, numImportRows As Integer)
Dim org As Range, dest As Range
Set org = wsImport.Range("B" & numTemplateHeaderRows + 1 & ":Y" & numImportRows + 1)
Set dest = ThisWorkbook.Worksheets("Sheet1").Range("B" & numTemplateHeaderRows + 1 & ":Y" & numImportRows + 1)
org.Copy
dest.PasteSpecial xlPasteAll
End Sub

Related

Using user range input for a formula

I am trying to create a VBA code that will pull the info to the Left (eventually the right) of a Hyphen based on a range and a cell given by the user.
EX:
Result A & Result B are what I am trying to get too.
I've tested everything in my code until this part and it all works. The entire thing works if I physically type in a cell address (i.e $D2 - I will need the column absolute, but the row relative so that it moves with the range selection). I just can't get it to work with the user input of the "Starting" variable. I need it to be user input because this code will be used on sheets set up completely different than this one. There is a good chance I am missing something obvious but I'm not seeing it #_#. Any suggestions?
**Sorry in advance for the long lines of code
Private Sub Seperate_XtoY_Click()
Dim iCol As Long
Dim iCount As Long
Dim i As Long
Dim Smaller As Range
Dim Bigger As Range
Dim Starting As Range
'Get number of columns that you want to insert with a user input box
iCount = InputBox(Prompt:="How many columns you want to add?")
'Get column NUMBER where you want to insert the new column
iCol = InputBox _
(Prompt:= _
"BEFORE which column do you want to add the new column(s)? (Enter the column number i.e A=1, B=2, C=3, etc)")
'loop to insert new column(s)
For i = 1 To iCount
Columns(iCol).EntireColumn.Insert
Next i
'Makes range variable "Starting" equal to the user input of a range (in this case just 1 cell)
Set Starting = Application.InputBox("Select the FIRST cell of the Original Range of #'s", "Obtain Range Object", Type:=8)
'Makes range variable "Smaller" equal to the user input of a range (where the info will actually populate)
Set Smaller = Application.InputBox("Select a range", "Obtain Range Object", Type:=8)
Smaller.Formula = "=IF(ISNUMBER(SEARCH(""½"", & Starting.Address(0, ""$"") &)),""0.5"",IF(ISNUMBER(SEARCH(""¼"",& Starting.Address(0, ""$"") &)),""0.25"",IF(ISNUMBER(SEARCH(""¾"",& Starting.Address(0, ""$"") &)),""0.75"",LEFT( &Starting.Address(0, ""$"")&, FIND(""–"",& Starting.Address(0, ""$"")&)-1))))"
End Sub
It turns out I had the right idea based on my last comment. I did need remove the variable completely out of the quotes (and then restart them), double check the placing of where I put those quotes, and use a different version of the .Address function to make only my column an absolute reference. All the other lines of code from above were all good, it was just the final line that needed to changed. Thank you #BigBen for giving me a push in the right direction. Looking at the program with fresh eyes also helped lol.
Smaller.Formula = "=IF(ISNUMBER(SEARCH(""½""," & Starting.Address(RowAbsolute:=False) & " )),""0.5"",IF(ISNUMBER(SEARCH(""¼"", " & Starting.Address(RowAbsolute:=False) & ")),""0.25"",IF(ISNUMBER(SEARCH(""¾"", " & Starting.Address(RowAbsolute:=False) & " )),""0.75"",LEFT( " & Starting.Address(RowAbsolute:=False) & " , FIND(""–"", " & Starting.Address(RowAbsolute:=False) & ")-1))))"
I also got the Right side function working too if anyone is interested:
Bigger.Formula = "=IF(ISNUMBER(SEARCH(""– ½""," & Starting.Address(RowAbsolute:=False) & ")),""0.5"",IF(ISNUMBER(SEARCH(""– ¼""," & Starting.Address(RowAbsolute:=False) & ")),""0.25"",IF(ISNUMBER(SEARCH(""– ¾""," & Starting.Address(RowAbsolute:=False) & ")),""0.75"",RIGHT(" & Starting.Address(RowAbsolute:=False) & ",LEN(" & Starting.Address(RowAbsolute:=False) & ")-FIND(""– ""," & Starting.Address(RowAbsolute:=False) & ")-1))))"
PLEASE NOTE for anyone who may want to use a variation of my code I used a slightly bigger hyphen than the typical hyphen ("-" vs "–")

VBA formula removing everything after second space

I was trying to copy from column D to column E first two words of each row but still can not find where the error is....
Range("E1:E" & lLastRow).Formula = "=LEFT(D1,FIND("" "",D1,FIND("" "",D1)+1)-1)"
Another option, instead of using a Formula, you can use the Split function.
Code
Dim i As Long, LastRow As Long
Dim WordsArr As Variant
' loop through rows
For i = 1 To LastRow
WordsArr = Split(Range("D" & i).Value, " ") ' use Split and space to read cell words to array
If UBound(WordsArr) >= 1 Then ' make sure the cell contents is at least 2 words
Range("E" & i).Value = WordsArr(0) & " " & WordsArr(1) ' insert only the first 2 words
Else ' in case there are less than 2 words
' do someting....
End If
Next i
End Sub
Try this instead ...
Range("E1:E" & lLastRow).FormulaR1C1 = "=LEFT(RC[-1],FIND("" "",RC[-1],FIND("" "",RC[-1])+1)-1)"
I find using R1C1 better for those sort of operations, especially given you want your references to be dynamic, not absolute.
Alternatively, add the formula you had normally and simply fill down.

Generate serial numbers and barcodes as per logic defined based on the count mention in certain cell

I need to generate lot numbers for my products and since my software doesn't auto generate them, I have defined a logic in Excel for the same. It is quite basic and combines data in 2 or more cells to create a unique code.
To be more specific, I shall introduce our operations to you. We have a few collection centers for our products and we require them to apply lot number labels onto their bags of coffee before transferring it to our main warehouse. I have created an excel sheet in which I enter the current date in one cell and select the name of the center in another which then generates a lot number for the same. For example, cell A1 has today's date and A2 has center 'MBR' selected. The formula in cell C2 =IF(A2="MBR","MB:"&TEXT(A1,"YYYYMMDD")&"-001",IF(A2="MAY","AY:"&TEXT(A1,"YYYYMMDD")&"-001",IF(A2="MZM","MM:"&TEXT(A1,"YYYYMMDD")&"-001",""))) shall give me a result as MB:20171010-001
Now comes the tricky part. I want to mention in cell A3 the number of lots to be generated. For example, if I say I want 10 labels, then the formula should give me 10 labels from "-001" to "-010." If possible, it could start with the number which I would define in possibly cell A4 and then give me the sequence as required.
Lastly, I use this info to generate barcodes using an add-on in excel which I downloaded from the internet which converts the text into barcodes and then I can print them. I have tried barcode fonts but they don't work at all. If you have another alternative to this where I could generate sequential lot numbers based on the logic defined and create barcodes for the same, please share it with me. If not, please give me a formula which will work with excel.
Enter your data in columns A - C, run the bit of sample code below, result is in column D. You can modify the code to suit your needs but here is a start for you:
Public Sub RunTags()
Dim oWS As Worksheet
Dim lRow As Long
Dim lNextTagRow As Long
Set oWS = Worksheets("Sheet1")
lRow = 2
lNextTagRow = 2
Do Until oWS.Range("A" & lRow) = ""
Select Case oWS.Range("A" & lRow)
Case "MBR"
PrintTags oWS, lNextTagRow, "MB:", oWS.Range("B" & lRow), oWS.Range("C" & lRow)
Case "MAY"
PrintTags oWS, lNextTagRow, "MA:", oWS.Range("B" & lRow), oWS.Range("C" & lRow)
Case "MZM"
PrintTags oWS, lNextTagRow, "MZ:", oWS.Range("B" & lRow), oWS.Range("C" & lRow)
End Select
lRow = lRow + 1
Loop
End Sub
.
Private Sub PrintTags(ByRef oWS As Worksheet, ByRef lTagRowStart As Long, sPrefix As String, lQty As Long, lStart As Long)
Dim x As Long
Dim dtNow As Date
dtNow = Now()
For x = lStart To lStart + lQty - 1
oWS.Range("D" & lTagRowStart) = sPrefix & Format(dtNow, "YYYYMMDD") & "-" & Format(x, "000")
lTagRowStart = lTagRowStart + 1
Next x
End Sub

Translate a worksheet formula in VBA

Can somebody help me to write this formula in excel VBA?
=IF(ISERROR(VLOOKUP(A3,Temp!$A$3:$A$595,1,FALSE)),A3,"0")
My code is getting stuck with :"syntax error"
Sub checkDuplitems()
Application.ScreenUpdating = False
Const top As Integer = 3
Dim bottom As Long
bottom = Sheets("Temp").Cells(Rows.Count, top).End(xlUp).row
With ThisWorkbook.Sheets("trash").Range("A" & top & ":A" & bottom)
.Formula = "=IF(ISERROR(VLOOKUP(A" & top & ",Temp!$B$" & top & ":$B$" & bottom & _
",1,FALSE)),A" & top & ", & '" 0" & ," '")"
.Value = .Value
.SortSpecial
End With
'Call something...
End Sub
You have a concatenation problem in the second line of the .Formula line.
To emulate the formula you have at the top of your question (which is wrong incidentally because you should be pointing to $B$3:$B$595 or something like that because your look up cell A3 should not be inside the VLOOKUP range).
Try this new .Formula line:-
.Formula = "=IF(ISERROR(VLOOKUP(A" & top & ",Temp!$B$" & top & ":$B$" & bottom & _
",1,FALSE)),A" & top & ", " & "0)"
Are you sure you want to use top as both the starting row in column A and the column to get the bottom row from the Temp worksheet? The important column on the Temp worksheet is column B (i.e. 2) not C (i.e. 3).
If you are putting formula(s) into Trash!A3:A595 that reference Trash!A3:A595 then these are circular references and cannot be resolved under normal conditions. I'll put the formulas into column Z.
If you are operating with Excel 2007 or newer then I would humbly propose this alternate that uses the worksheet's IFERROR function and does not attempt to make text out of the 0 returned value.
Const top As Integer = 3
Dim bottom As Long
bottom = Sheets("Temp").Cells(Rows.Count, "B").End(xlUp).Row '<~~change here
With ThisWorkbook.Sheets("trash")
With .Range("Z" & top, .Cells(Rows.Count, "A").End(xlUp).Offset(0, 25))
.Formula = "=IFERROR(VLOOKUP(A" & top & ", Temp!$B$" & top & ":$B$" & bottom & _
", 1, FALSE), 0)" '<~~ big change here
.Value = .Value
End With
End With
It is also curious as to why the number of rows of formulas in the Trash worksheet must be governed by the number of rows of data in the Temp worksheet. I would have thought that the number of values in column A of the Trash sheet should govern how many formulas go into the Trash worksheet.

Excel VBA code mid function

I have the following string "123 - 456789". What I am trying to do is find a way to only capture the remaining characters after the second space - "456789" - regardless the length of the string.
I have the follow set of code:
For leftLoop = 2 To leftNumberOfCells
Range("A" & iRow) = Split(Range("B" & iRow).Value, " ")
Range("B" & iRow) = Mid("B" & iRow, InStr("B" & iRow, " "), 100)
iRow = iRow + 1
Next leftLoop
The code line "Range("B" & iRow) = Mid("B" & iRow, InStr("B" & iRow, " "), 100)" is what I tried, among other ways (from searching online, but I can't seem to get it to work.
I have two questions:
Does someone know what the correct code should be? and...
Can I reference the cell where the string is located and replace it in that same cell after doing the mid function without having to temporarily put it into another cell and copy and paste it back? For example, my string "123 - 456789" is in cell B2, is there a way to code it so I can reference cell B2 and simultaneous replace the cell B2 with "456789" and not having to place it in another cell then copy and paste it back into B2. I hope you get what i'm asking.
Thanks for you help!
This addresses part 2.
Sub strings()
Dim replace As String
Dim bCell As Range
For leftLoop = 2 To leftNumberOfCells
Set bCell = Range("B" & iRow)
replace = Mid(bCell, InStr(bCell, "-") + 2, 100)
Range("B" & iRow) = replace
iRow = iRow + 1
Next leftLoop
End Sub
Try this:
result = Split(TextToSplit, " ", 3)(2)
Split(TextToSplit, " ", 3) will split the text on spaces, returning a zero-based array. The last argument 3 limits the splitting to 3 portions: before the first space, between the first and second space, and everything else. The (2) at the end of the statement returns the last element of the array.
Hope that helps

Resources