trimming of white spaces before values - vba

I am having an issue trimming white space characters. When I enter a value and give spaces before and after the value in Excel, I see spaces surrounding it but I should not see those extra spaces.
I would like to remove these spaces but I'm not sure how to achieve this, here is the output that I'm getting currently:
ServerName = " testing "
but the generated output should be like this...
ServerName = "testing"
Here is the code that I'm using in my project:
If Sheets(Itm).Cells(i, 2) = "Required1" Then
MsgBox "Enter the value for required field : " & Sheets(Itm).Cells(i, 1)
Return
End If
Value = Replace(Sheets(Itm).Cells(i, 4).Value, vbLf, " ")
'Value = Sheets(Itm).Cells(i, 4).Value

Try this (Untested)
Value = Trim(Sheets(Itm).Cells(i, 4).Value)
Value = Application.WorksheetFunction.Clean(Value)
Print #1, Sheets(Itm).Cells(i, 1) & "=" & Value
Here is a sample code to understand how it works...
Sub sample()
Dim sample As String
sample = "Sid"
Debug.Print Len(sample) '<~~ This will give you 3
sample = " " & vbNewLine & sample & vbNewLine & vbCrLf & vbLf
Debug.Print Len(sample) '<~~ This will give you 11
sample = Trim(sample)
Debug.Print Len(sample) '<~~ This will give you 10
sample = Application.WorksheetFunction.Clean(sample)
Debug.Print Len(sample) '<~~ This will give you 3
End Sub

Replace:
Print #1, Sheets(Itm).Cells(i, 1) & "=" & Value
With:
Print #1, Replace(Sheets(Itm).Cells(i, 1) & "=" & Value," ","")

Related

operate cells with other sheet with sheet().cells() format

I need iterate sheets that plus values in their cells in other sheet, the names of the "sheets" are save in sheet().index= man_prov and i iterate that. The code works but appears a window that requets "refresh values to the sheets" and the objetive cell value finally is "#¿NAME?". The code is:
For k = pfila_mprov + 1 To ufila_mprov
sn = Sheets(man_prov).Cells(k, 2)
h = Sheets(sn).Index
Select Case k
Case ufila_mprov
suma = suma & " " & Sheets(h).Name & "!" & Sheets(h).Cells(4, 4).Address & ""
Case Else
suma = suma & " " & Sheets(h).Name & "!" & Sheets(h).Cells(4, 4).Address & ","
End Select
Next k
Sheets(pro_pack).Cells(16, 4).Formula = "=sum(" & suma & ")"
End If
i need use the format sheets().cell() to iterate, and finally plus the values saved in "suma" .
Thanks.

How to use variables to set pivot table Function parameters with VBA?

I would like to use variables to specifying parameters of pivot table. Most of them are working correctly, but 2 of them not. The “function” parameters “xli” and “ValueFilterQuant(pos)” don’t come up with any values. I tried it write between quotation marks and quotation marks-& but nothing happened. Is there any method to set Function parameters with variables? This is the snippet of code:
For pos = 1 To UBound(ValueQuant)
If ValueQuant(pos) = "Work" Then
xli = "xlSum"
Label = "Sum of "
Else
xli = "xlCount"
Label = "Count of "
End If
ActiveSheet.PivotTables("PivotTable1").CubeFields.GetMeasure "[database].[" & ValueQuant(pos) & "]" _
, xli, "" & Label & "" & ValueQuant(pos) & ""
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
" PivotTable1").CubeFields("[Measures].[" & Label & "" & ValueQuant(pos) & "]"), "" & Label & "" & ValueQuant(pos) & ""
With ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"[Measures].[" & Label & "" & ValueQuant(pos) & "]")
.Caption = "" & ValueFilterQuantaf(pos) & "" & ValueQuant(pos) & ""
.Function = ValueFilterQuant(pos)
End With
Next
The code is incomplete. I don't know where ValueFilterQuant(pos) is coming from.
I suspect that like xli = "xlSum" it is returning a string variable, but the thing is that those parameters should not be strings. They are numbers that are derived from an XlConsolidationFunction enumeration.
So something like:
If ValueQuant(pos) = "Work" Then
xli = XlConsolidationFunction.xlSum '-4157
Label = "Sum of "
Else
xli = XlConsolidationFunction.xlCount '-4112
Label = "Count of "
End If
Same thing needs to happen for ValueFilterQuant(pos).
Note that it is more work to derive a dynamic enumeration at runtime through a string. I guess that you are reading a string value in off a worksheet or similar process.
You could set them up in a dictionary beforehand, and pick out the numbers that way.
The list of values is here: https://msdn.microsoft.com/en-us/library/office/ff837374.aspx

Fill a column from a concatenate range

What I have this far is below.
Range("F4").Value = Range("D4").Value & " x " & Range("E4")
This is creating a concatenate in Column F for me. This is working fine for the individual cell but I would like this to continue concatenating down until it hits an empty cell.
I have tried looping without success.
below is an image of the sheet
Set Concat= Rows(4)
concatstring =""
For i = 1 To Concat.Cells.Count
If Concat.Cells(i).Text <> "" Then
Concatstring = concatstring & " x " & Concat.Cells(i).Text
Else
Exit for
End If
Next
Concat.cells(I).text = concatstring
This should do it. Let me know if you still have problem.
Try this...
i=4
Do while(Range("D" & i).Value<> "")
Range("F" & i).Value = Range("D" & i).Value & " x " & Range("E" & i)
Loop

Excel vba variable logic operator

I have a spreadsheet where the user can define some rules, but I'm struggling with getting the log to work. I want difference results based on what the user wants, but ideally I want to stay away from have to but multiple select cases in or if lines.
What I have Is this (Simplified - It's in a loop so the values will change for every row - I'm just using an example):
The operator can vary, it could be ">","=>" etc.
Field1Value = "Football"
Operator1 = "="
Rule1 = "Football"
If Evaluate(Field1Value & Operator1 & Rule1 ) Then
'Run My Code
End If
So in the above example the logic would be true and my code would run, but I'm getting a type mismatch error.
Has anyone any ideas?
Thanks
Chris
********UPDATE********
Here's the full Code:
Workbooks(MasterWB).Activate
Sheets("Rules").Select
NoRules = Sheets("Rules").Range("J6").End(xlDown).Row
For a = 7 To NoRules
Field1 = Workbooks(DataWB).Sheets(DataWS).Rows(1).Find(Workbooks(MasterWB).Sheets("Rules").Cells(a, 10), , xlValues, xlWhole).Column
Operator1 = Sheets("Rules").Cells(a, 11)
Rule1 = Sheets("Rules").Cells(a, 12)
Operator = Sheets("Rules").Range("J5").Cells(a, 13)
Field2 = Workbooks(DataWB).Sheets(DataWS).Rows(1).Find(Workbooks(MasterWB).Sheets("Rules").Cells(a, 14), , xlValues, xlWhole).Column
Operator2 = Sheets("Rules").Cells(a, 15)
Rule2 = Sheets("Rules").Cells(a, 16)
HighlightColumn = Workbooks(DataWB).Sheets(DataWS).Rows(1).Find(Workbooks(MasterWB).Sheets("Rules").Cells(a, 17), , xlValues, xlWhole).Column
HighlightColour = Workbooks(MasterWB).Sheets("Rules").Cells(a, 17).Interior.ColorIndex
Workbooks(DataWB).Activate
With Workbooks(DataWB).Sheets(DataWS)
.Select
Lastrow = .UsedRange.Rows.Count
For b = 2 To Lastrow
Field1Value = .Cells(b, Field1).Value
If Evaluate(Field1Value & Operator1 & Rule1) Then
.Cells(b, HighlightColumn).Interior.ColorIndex = HighlightColour
End If
Next b
End With
Next a
Assuming that you're expecting "Football" = "Football" yields True, then give this a try:
If Evaluate("""" & Field1Value & """ " & Operator1 & " """ & Rule1 & """") Then
Note, I enclosed my strings in quotes - you need to pass those to Evaluate()
Actually, according to my reading of the MS Docs, I don't think this will work.
Evaluate(Name)
Name: A formula or the name of the object, using the naming convention of Microsoft Excel. The length of the name must be less than or equal to 255 characters.
What is the definition of "Football"? Is it a simple text string? My reading indicates that Evaluate() will execute a built in function or a UDF, but not a simple comparison.
Hold on I don't mean to steal Credit from FreeMan but following worked for me:
Sub test()
Dim Field1Value As String
Dim Operator1 As String
Dim Rule1 As String
Dim test As Range
Dim Passed As Boolean
Field1Value = "Football"
Operator1 = "="
Rule1 = "Football"
Passed = Evaluate("=" & """" & Field1Value & """" & Operator1 & """" & Rule1 & """")
'Different way of achievieng same thing ignore this if you want to
Set test = Range("A1")
test.Formula = "=" & """" & Field1Value & """" & Operator1 & """" & Rule1 & """"
Passed = test.Value
MsgBox Passed
End Sub
I tried it a with several values and operator and it works fine.
So I would only correct FreeMan by adding "=" & as first part of Evaluate.
So to make this more concise I'm saying write this :
Evaluate("=" & """" & Field1Value & """" & Operator1 & """" & Rule1 & """")
Try something like below:
Field1Value = "Football"
Operator1 = "="
Rule1 = "Football"
Dim x As Variant
strEvaluate = Chr(34) & Field1Value & Chr(34) & Operator1 & Chr(34) & Rule1 & Chr(34)
x = Evaluate("IF(" & strEvaluate & ",1,0)")
if x = 1 then
'Run your code
end if
Or instead of 1 and 0 use TRUE and FALSE. My language is not English. But I think this works also.
x = Evaluate("IF(" & strEvaluate & "," & True & ", " & False & ")")
if x = TRUE then
'Run your code
end if

Address function returns two ":" for single cell

I'm having some trouble understanding some strange behavior. The .address property of the range class is returning a cell in "Cell:Cell" format. Both (1) and (2) give the address in the form of "$A$1:$A$1" instead of simply "$A$1". A snippet of code is listed below:
With Sheet1
Set r = .Range("MyRange")
'(1)*
Debug.Print r.Address
r.Formula = "= 1 + 1"
For i = 1 To 47
Set r = r.Offset(0, 1)
'above
r1 = r.Offset(-1, 0).Address(True, False)
'above to the left
r2 = r.Offset(-1, -1).Address(True, False)
'to the left
r3 = r.Offset(0, -1).Address(False, False)
'(2)*
Debug.Print r.Address & "gets: " & r1 & "+" & r2 & "+" r3
Next
End With
Debug.Print in either case prints in the format:
"$D$10:$D$10 gets: $D$9:$D$9 + $C$8:$C$8 + ... " and so on.
Note:
I'm not saying that (1) and (2) print the same thing.. they both print as expected, it's just the format of what is printed is repeated twice as a range of one cell.
Any thoughts would be greatly appreciated - B
EDIT: When I save and close out of the workbook, the behavior stops and it returns to printing addresses as expected "$D$10 gets: ... "
Please try the following:
Sub dural()
Dim r As Range
Set r = Range("A1")
s = r.Address
s = s & vbCrLf & r.Address(1, 1)
s = s & vbCrLf & r.Address(1, 0)
s = s & vbCrLf & r.Address(0, 1)
s = s & vbCrLf & r.Address(0, 0)
MsgBox s
End Sub
You should see no colons.