This is my first month with VBA and I've overcome so many obstacles and reduced walls of code with loops, made code pretty much uncrashable, even when user using macro doesn't know what he/she is doing, but I am stuck with this:
If i = 1 Or i = 2 Then
Columns("F:F").Select
Selection.Replace ".", ","
Selection.NumberFormat = "dd\/mm\/yyyy hh:mm:ss"
End If
For some reason the result of replacement of:
438595.73402778 is this 43859573402778
I tried different variations from recording the macro to gradually simplifying the code and ended up with above. Always same result. What am I missing here?
The code is kind of complex, because I have to take data from 6 temporary workbooks into 4 sheets, secure it, depending on user login etc. It works great, but I thought, let's make it even better, because 3 out of those 6 qlikview workbooks have incorrect format in 1 of 4 time tracking columns.
It's kind of sad that I had to write my first post for such thing
I assume your current data is actually string data looking like numeric values. If column F is formatted to General and these "string" numbers appear, then you could change that around using Range.TextToColumns. For example:
Sub Test()
Dim lr As Long, rng As Range
With Sheet1
'Get last used row of column F and set rng
lr = .Cells(.Rows.Count, 6).End(xlUp).Row
Set rng = .Range("F2:F" & lr)
'Replace dot with comma and change to numeric
rng.TextToColumns Destination:=Range("F2"), DataType:=xlFixedWidth, DecimalSeparator:=".", ThousandsSeparator:=","
rng.NumberFormat = "dd\/mm\/yyyy hh:mm:ss"
End With
End Sub
Seems like you have different decimal separator settings in Excel files.
Go to Options-> extended-> use systems decimal separator.
This option may be off on some workbooks and ,is set as decimal separator.
to fix:
If Application.International(xlDecimalSeparator) = "," Then
MsgBox "Wrong decimal separator(,)!!"
Application.UseSystemSeparators = True
End If
If you want to output dot but leave comma the separator use
With ThisWorkBook.WorkSheet("Sheet1")
MsgBox Str( .Range("A1"))
End With
See Using VBA to detect which decimal sign the computer is using
Related
I have the following issue.
One of my sheets holds a column that contains values stored as text (e.g. value as 1,22 stored as a text). Currently I use the following Code to convert those entries to values:
Sub Convert()
Range(Cells(2, "K"), Cells(Rows.Count, "K").End(xlUp)).TextToColumns DataType:=xlFixedWidth, DecimalSeparator:=","
End Sub
If I run the macro once the result is fine. However if I run to macro a second time (after I already converted the text to values with the code shown above). The numbers change their format from the comma "," as the decimal separator to a dot "." as a decimal separator (e.g. 1,22 --> 1.22).
This is a problem, because my region uses the comma.
Does anybody know how to prevent this from happening?
Kind regards
Sombrero
Here Screenshots:
Original data#
After first time text2columns:
After second time text2columns:
You original data are strings, and running TextToColumns converts them into numbers. When you run TextToColumns a second time, Excel needs to convert those numbers first into strings.
I can only guess about the internal logic of this conversion, but it wouldn't surprise me if this is not using any regional settings.
Anyhow, I would say it's not a good idea to use the TextToColumns command on numeric values. Use a filter to get only the cells containing text:
Dim r As Range
set r = Range(Cells(2, "K"), Cells(Rows.Count, "K").End(xlUp))
On Error Resume Next ' To prevent runtime error "No cells found"
Set r = r.SpecialCells(xlCellTypeConstants, xlTextValues)
If err.Number = 1004 then exit sub
On Error Goto 0
r.TextToColumns DataType:=xlFixedWidth, DecimalSeparator:=","
i wrote a code in VBA to change values in a range from text into general (number). it works fine, however there is one issue. when i checked all the column values, only the string with an integer value ("2345") is changed to integer (2345) but the strings with float values ("123.456") didn't change at all, the type changed into General but the value stay the same.
here is the vba code
If (ws.Name = "TB") Then
shTB.Activate
[A:A].Select
With Selection
.NumberFormat = "General"
.Value = .Value
End With
results as the table below, still the float values didn't change at all. as you can see only row 119 changed into Number or integer.Any suggestion or help is appreciated highly!
It is clear from your results that there is a mis-match between the text format of your data and your Locale settings.
You data appears to have come from a source in which the comma is the decimal separator rather than the period. Try:
Sub dural()
With Range("A:A")
.NumberFormat = "General"
.Replace ",", "."
.Value = .Value
End With
End Sub
if that "." stands for thousands separator then just remove it
With shTB.Range("A:A")
.Replace what:=".", replacement:=vbNullString
.NumberFormat = "General"
End With
BTW, as you see you don't need to select anything: just act on its direct reference
I have a text based system with people's names, and I need to copy and paste the first 4 cells (not a problem) and the last 5 cells to a different worksheet for analysis.
The problem arises with the transfer from the text based system the data is presented in, to the spreadsheet when it comes to people with spaces in their surname (ie, Da Silva). I use text to columns, which will give me a variant number columns, depending on the number of spaces in the name which is an issue.
I already have a crude solution, but the time it takes and the jumping about between screens while the macro is running looks very unprofessional. I don't get much spare time at work, and I don't have the tools to test this properly at home.
Can anyone help me get this to loop until the last empty cell, and basically neaten it up a little?
The code, which repeats 300 times, is as following:
Sheets("Late list Sorting").Select
Range("A2").End(xlToRight).Select
Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(0, -5)).Select
Selection.Copy
Sheets("Late list").Select
Range("D4").Select
ActiveSheet.Paste
(...Repeat until...)
Range("A300").End(xlToRight).Select
Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(0, -5)).Select
Selection.Copy
Sheets("Late list").Select
Range("D302").Select
ActiveSheet.Paste
Sheets("Late list Sorting").Select
If you only want the values (not formulae or formatting) then you can simply use Value=Value...
Dim i As Long, sWs As Excel.Worksheet, tWs As Excel.Worksheet
Set sWs = ThisWorkbook.Worksheets("Late list Sorting")
Set tWs = ThisWorkbook.Worksheets("Late list")
For i = 2 To 300
tWs.Range(tWs.Cells(i + 2, 4), tWs.Cells(i + 2, 8)).Value = sWs.Range(sWs.Cells(i, 1).End(xlToRight), sWs.Cells(i, 1).End(xlToRight).Offset(0, -5)).Value
Next
it is inefficient to use .Select, here's a great resource: How to avoid using Select in Excel VBA
To eliminate the screen flashes, put this at the beginning of your code. Remember to turn it back to true at the end.
Application.ScreenUpdating = False
You want to use a loop, where the variable i becomes the row number you will reference like so:
Range("A" & i).Value...
There are many ways to loop, here is one example:
For i = 1 to 300
//All your code here
Next i
I am new to vba coding (and coding in general) but I have started doing a small macro that transfers values of a csv file into an excel file.
My next step is to remove the quotation marks in each cell. I have tried these lines of codes in my sub:
Dim Table As Range
Dim Cell As Variant
Set Table = Range("A1:currentregion")
For Each Cell In Table
cell.value2 = Replace(cell.value2,""","") *I get a syntax error here*
Next Cell
I know this is very basic but I can't find a solution on the net or using the macro recorder. If anybody could tell me what I am doing wrong and also what code I could use to change the value in a cell that contains a string of numbers into a numeric value?
Thanks!
You don't need to loop through each cell. The Range("A1").CurrentRegion may be operated on as a whole.
With Range("A1").CurrentRegion
.Replace What:="""", Replacement:=vbNullString, LookAt:=xlPart
End With
Note that to look for a single quote (e.g. ") you need 4 quotes in a row. An alternative is Chr(34) as a quote symbol is the 34th ASCII character.
Addendum:
With regard to the second portion of your question, changing text that looks like a number to actual numbers is best done with a quick Text to Columns ► Fixed Width command. Each column would have to be run through individually but this can be accomplished within the .CurrentRegion.
Dim c As Long
With Range("A1").CurrentRegion
.Replace What:="""", Replacement:=vbNullString, LookAt:=xlPart
For c = 1 To .Columns.Count
.Columns(c).NumberFormat = "General"
.Columns(c).TextToColumns Destination:=.Columns(c), _
DataType:=xlFixedWidth, FieldInfo:=Array(0, 1)
Next c
End With
There is the question of what number format the columns were in to begin with. If they were Text (e.g. '.NumberFormat = "#"` then removing the quotes is not going to convert them to true numbers. I've added a reversion to the General number format to accommodate this. If you have existing number formats that you wish to keep, there are more precise ways of reverting the number formats of some of the cells.
Cell.Value2 = Replace(Cell.Value2, Chr(34), "")
There always is a workaround, this one is referencing via character code.
You should dim Cell as Range. Also it's not a very good idea to name a variable using a VBA syntax element. Use MyTable and MyCell instead.
And to set the range better use
Set MyTable = [A1]
For Each MyCell In MyTable.CurrentRegion
...
So I have approx. 8.000 URLs, and most of them are missing a comma before their date-part, and I need that damn comma to pass my undergrad.
Examples:
(...)_employee_declarations_legal_complaint_and_motions_2009 (should be: motions,_2009)
(...)/wiki/Xinhua_Presidential_Express_18_Jun_2009 (should be: Express,_18_Jun_2009)
(...)guide_for_law_enforcement_23_Dec_2008 (should be: enforcement,_23_Dec_2008)
And so on. I need to insert the commas automatically in Excel. Is that even possible? Could you tell it to insert a comma before a ## _ text _ #### or something like that? Replace won't work, when it's different dates.
The biggest problem is, that I'm not a programmer. I'm an undergraduate political science major trying to do a statistical analysis of WikiLeaks.
BTW: The problem is not that I imported it wrong (from CSV to Excel), there's lots of commas other places. The problem is that I use import.io as a datascraper, and it's probably their bug.
You could use a text editor on your CSV file (if it supports Perl-style regexes) and tell it to replace
_(?:\d{1,2}_[A-Za-z]{3}_)?(?:19|20)\d{2}\b
with ,\0.
If the majority are in the format i.e. '_23_Dec_2008', I assuming the date is always at the end of the string.. try
=REPLACE(A1,FIND(RIGHT(A1,12),A1,0,",")
The 12 refers to the number of characters in the date i.e. date format '_23_Dec_2008' is 12
The 1 refers to the start character of the string to be amended i.e. from _
The 0 refers to the number of characters to amend i.e. none
The "," adds the comma in front of the underscore
Just need to amend first row to those dates of different lengths
Hope this helps
In the comments you've mentioned that there are about twenty different formats. Here are three (two because your sample was ambiguous about d vs. dd).
Sub fix_urls()
Dim fw As String, rw As String, i As Long, iOldCalc As Long
On Error GoTo Fìn
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
With ActiveSheet.UsedRange.Cells
'replace the days both ways as the sample data was ambiguous
For i = 1 To 31
fw = Format(i, "_00_") 'find what
rw = Format(i, "\,_00_") 'replace with
.Replace What:=fw, Replacement:=rw, LookAt:=xlPart, MatchCase:=False
fw = Format(i, "_0_") 'find what
rw = Format(i, "\,_0_") 'replace with
.Replace What:=fw, Replacement:=rw, LookAt:=xlPart, MatchCase:=False
Next i
For i = 2000 To 2014
fw = Format(i, "_0000") 'find what
rw = Format(i, "\,_0000") 'replace with
.Replace What:=fw, Replacement:=rw, LookAt:=xlPart, MatchCase:=False
Next i
End With
Fìn:
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Plan your attack carefully. Look closely at the twenty-odd formats and make sure that one could not supercede a false positive on another. Often there is a prescribed order that replacements must be performed in.
For example, in the three format masks used above, if the _dd_ was only _dd then _20 with xlPart would supercede any _2000, _2001, _2002, etc. Just be careful and keep a few backups.
Just a reminder to my comment above; with these inserted commas you need to use a text qualifier so that a comma in the middle of a text field does not break that field's value into two fields. Excel should do this for you on a simple Save As ► .CSV but it looks into the data a preset number of rows to determine whether or not to use quoted identifiers on a field. This look-ahead value can be raised through the registry but that is generally not necessary.