How do I left justify my columns in Excel programmatically in VB? I have a VB program that is writing an excel file based off of certain information. I have tried using:
oSheet.Columns.HorizontalAlignment.Left()
This works against columns with text. I have multiple columns that are strictly numbers. This function will not work against columns with Numeric Cells.
Below is the MissingMemberException I keep getting:
Public member 'Left' on type 'Integer' not found.
Range.HorizontalAlignment is a property that requires an integer constant. Left is xlLeft. xlLeft evaluates to -4131. xlDistributed is -4117, xlRight is -4152, xlCenter is -4108, and xlJustify is -4130.
HorizontalAlignment should work for both text and numbers. You should specify the value for the alignment though since it is a property.
Although the #Banjoe answer will work, the documentation specifies the following valid constants for HorizontalAlignment property:
xlHAlignCenter
xlHAlignCenterAcrossSelection
xlHAlignDistributed
xlHAlignFill
xlHAlignGeneral
xlHAlignJustify
xlHAlignLeft
xlHAlignRight
I used the following, and it worked great for me:
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Add()
objExcel.Cells(1, 1).Value = "Some data"
objExcel.Cells(1, 2).Value = "More data"
Set objWorksheet = objWorkbook.Worksheets(1)
objExcel.Columns(2).Select
objExcel.Selection.EntireColumn.HorizontalAlignment = 2
Related
I am creating a macro using both vbscript and vba, this macro is being called by the script code and works well but when I try to select a value outside the macro itself, I keep getting an error about the way im trying to set the value.
I have named the dropdownlist as "Result" and when I try to set the value it does not work, I also tried with the default name "DropDownList" , but none of those options seems to work, maybe i am missing object references.
I already declared the objects that I need
Set objWord = CreateObject("Word.Application")
Set activeDoc= objWord.ActiveDocument
activeDoc.FormFields("Result").DropDown.Value = 2
The error i am getting right now is that "The Requested memeber of the coleection does not exist."
The only solution I can come up with is to set the value when I'm creating the dropdown in the macro:
ActiveDocument.Tables(1).Cell(Row: = 4, Column: = 4).Select
Set objCC =
Selection.Range.ContentControls.Add(wdContentControlDropDownList)
With objCC
.Title = "Result"
.Tag = "Result"
.DropdownListEntries.Add("Passed", "Passed").Select
End with
I got everything messed up, but in the end I realized what was my mistake. I wasn't using the tag so the Item was loose, I had to use the index of the correct content control
Set objCc = activeDoc.ContentControls.Item(5)
Set objLe1 = objCc.DropdownListEntries.Item(1)
objLe1.Select
Thanks very much for your part of code, I have so much trouble to find how to do this !
I add just :
With ThisDocument.tables(blabla).Cell(x,y)
Set objCc = .Range.ContentControls.Item(1)
Set objLe1 = objCc.DropdownListEntries.Item(2)
objLe1.Select
End With
And it works perfectly within my project ! Ty again, see you !
The FormulaR1C1 Method doesn't work as it's supposed to.
objExcel = CreateObject("Excel.Application")
objWorkbook = objExcel.Workbooks.Add
Dim Formula As String
Formula = "=SUMME(Z1S1;Z2S1)"
For i = 1 To 5 Step 1
objWorkbook.Worksheets("Tabelle1").Cells(i, 1).FormulaR1C1 = 5
objWorkbook.Worksheets("Tabelle1").Cells(i, 5).FormulaR1C1 = "Text"
objWorkbook.Worksheets("Tabelle1").Cells(i, 3).FormulaR1C1 = Formula
Next
This should give me 10 in the third column 5 times, but it doesn't. I even tried it with:
Formula = "=SUMME(Z[0]S[-2];Z[1]S[-2])"
but that doesn't work either. The Loop just breaks when coming to the assigment line :( . If I try it with
Formula = "=SUMME(Z1S1,Z2S1)"
It executes completely but it doesn't work for excel because then it says =SUMME('Z1S1';'Z2S1') in the Excel Field
You have to use the Range.FormulaLocal property or Range.FormulaR1C1Local property if you plan to use a string that contains non-EN-US function. VB.Net expects a EN-US formula and will translate that to the regional language of the worksheet.
Formula = "=SUM(A1, B2)"
'or depending on your requiements,
Formula = "=SUM(A1:B2)"
.Formula = Formula
Formula = "=SUM(R1C1, R2C2)"
'or depending on your requiements,
Formula = "=SUM(R1C1:R2C2)"
.FormulaR1C1 = Formula
Formula = "=SUMME(Z1S1;Z2S1)"
'or depending on your requirements,
Formula = "=SUMME(Z1S1:Z2S1)"
.FormulaLocalR1C1 = Formula
Don't confuse xlA1 cell references with xlR1C1 references. R23 would mean Cells(23, 18) in xlA1 and 23:23 in xlR1C1.
Note that using the Range.Formula property or Range.FormulaR1C1 property enforces the use of a comma (EN-US standard) instead of a semicolon as a system list separator.
Range.Formula property
Range.FormulaR1C1 property
Range.FormulaLocal property
Range.FormulaR1C1Local property
In my code, I have declared these variables:
Dim Field_Name, Datatype, row As Integer
Then, inside a For loop, I have this code:
Field_Name = Worksheets(i).UsedRange.Find("Field Name").Column
Datatype = Worksheets(i).UsedRange.Find("Datatype").Column
row = Worksheets(i).UsedRange.Find("Field Name").row + 1
However, that code throws the "Object variable or with block variable not set" run-time error. According to the API, the Range.Column and Range.row property is a read-only Long. I have tried making the datatype of my variables to Long, but with no success. It would appear that VBA expecting me to do
Set Field_Name = Worksheets(i).UsedRange.Find("Field Name").Column
Set Datatype = Worksheets(i).UsedRange.Find("Datatype").Column
Set row = Worksheets(i).UsedRange.Find("Field Name").row + 1
However, said variables are not objects, so doing that throws the "Object required" compile error.
Any help with this would be greatly appreciated. If you're not sure about how to fix it, then any workarounds or alternative ways to get the column number and row number of a cell would be greatly appreciated.
Even though this is an old question, I'd like to say something too.
I had the same problem to get this error while using the .Find method. I came to this question and so others will do the same.
I found a simple solution to the problem:
When Find does not find the specified string it returns Nothing. Calling anything directly after Find will lead to this error. So, your .Column or .row will throw an error.
In my case I wanted an Offset of the found cell and solved it this way:
Set result = Worksheets(i).Range("A:A").Find(string)
If result Is Nothing Then
'some code here
ElseIf IsEmpty(result.Offset(0, 2)) Then
'some code here
Else
'some code here
End If
Simplified answer:
Your .Find call is throwing the error.
Simply adding "Set " to that line will address the problem. i.e...
Set Datatype = Worksheets(i).UsedRange.Find("Datatype").Column
Without "Set," you are attempting to assign "nothing" to a variable. "Nothing" can only be assigned to an object.
You can stop reading here unless you would like to understand what all the other (valid, worthwhile) fuss was about your code.
To paraphrase all of the (warranted) code critiquing, your Dim statement is bad. The first two variables are not being "typed" and end up as variants. Ironically, this is why the solution I just described works.
If you do decide to clean up that Dim statement, declare DataType as a variant...
Dim DataType as variant
What about the below code:
For i = 1 to 1 ' change to the number of sheets in the workbook
Set oLookin1 = Worksheets(i).UsedRange
sLookFor1 = "Field Name"
Set oFound1 = oLookin1.Find(What:=sLookFor1, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
If Not oFound1 Is Nothing Then
Field_Name = oFound1.Column
RRow = oFound1.Row +1
' code goes here
Else
Msgbox "Field Name was not found in Sheet #" & i
End If
Set oLookin2 = Worksheets(i).UsedRange
sLookFor2 = "Datatype"
Set oFound2 = oLookin2.Find(What:=sLookFor2, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
If Not oFound2 Is Nothing Then
DataType = oFound2.Column
' code goes here
Else
Msgbox "Datatype was not found in Sheet #" & i
End If
Next i
This is an old old post - but I ran across it when I was having trouble figuring out why I suddenly could not import a PDF export into my excel sheet.
For me the problem was a row I was trying to match on was merged - did a simple unmerge for the entire sheet first and it worked like a charm.
'////// Select and open file
FieldFileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*") 'pick the file
Set frBook = Workbooks.Open(FieldFileName, UpdateLinks:=0, ReadOnly:=True, AddToMru:=False)
For Each mySheet In frBook.Worksheets
mySheet.Cells.UnMerge
Next mySheet
I have some cells with Data Validation. Because the dropdown list is small and hard to read, I have a button which opens a list box and populates it with the cell's Data Validation list.
Dim btnAddToList As OLEObject
Public lboTemp As OLEObject
Set btnAddToList = ws.OLEObjects("btnAddToList")
Set lboTemp = ws.OLEObjects("TempListBoxS")
Set Field = Selection ' This is always cell $D$1, $D$2, or $D$3
btnAddToList.Visible = False
'Create a named range "temp"
ActiveWorkbook.Names.Add Name:="temp", RefersTo:=Field.Validation.Formula1
' open list box
' position list box
' load it with "temp"
With lboTemp
'show the listbox with the list
.Visible = True
.Left = Field.Left
.Top = Field.Top + 50
.ListFillRange = "temp"
.Object.MultiSelect = 0 ' Single select
On Error GoTo errHandler
prev = .LinkedCell
If prev <> "" Then prev = prev & ": " & Range(.LinkedCell).Value ' for debugging
.LinkedCell = Field.Address 'SOMETIMES THIS GIVES Err 440: could not set property value, invalid property value
.Width = Field.Width + 5
.Height = WorksheetFunction.Min(270, .Object.ListCount * 20) 'field.Height + 5
End With
As noted in the comment above, I sometimes, but not always, I get an error when the LinkedCell is supposed to be populated by with the Field.Address.
This code is used by six different cells (D1:D3 on two different worksheets), but the error only appears to occur when one of the D1 cells is the one selected. Those cells have one other thing in common: their data validation lists, respectively, are:
='Category Table'!$F$2:$F$31 and
='Category Table'!$F$32:$F$41
The other four cells -- which don't get the error -- use a complicated dynamic range that references a different table on the "Category Table" sheet. (I don't really think this has anything to do with my problem, but I don't see anything else those cells have in common)
If no one can give me an answer, I'd appreciate some advice on how to track down an intermittent problem.
Thanks!
Maybe the problem is the return of Field.Address. The .Adress property returns, by default, with the absolute value of row and column. You can try Field.Address(RowAabsolute:=false, ColumnAbsolute:=false) . Hope this help.
and sorry my english.
I managed to stop this issue by ensuring that the linked cell was empty before creating the reference.
Disclaimer: It's been a few years since I worked (a lot) with VBA, so this might be an issue caused by confusing myself with what is essentially a very different language from what I usually deal with.
So; I've got a workbook (Excel 2010) with multiple sheets (20+), most of whom are multi-page. To make things easier when printing everything, I want to add some sheet-specific headers with amongst others the name of the sheet, number of pages and so on.
I've written a tiny function that should (in theory) do this for me by iterating over all the sheets setting the header. However, for some reason it only works if the header is empty; if it already has a value it refuses to overwrite for some unknown reason.
Dim sheetIndex, numsheets As Integer
sheetIndex = 1
numsheets = Sheets.Count
' Loop through each sheet, but don't set any of them to active
While sheetIndex <= numsheets
Dim sheetname, role, labeltext As String
sheetname = Sheets(sheetIndex).name
role = GetRole(mode)
labeltext = "Some text - " & sheetname & " - " & role
With Sheets(sheetIndex).PageSetup
.LeftHeader = labeltext
.CenterHeader = ""
.RightHeader = "Page &[Page] / &[Pages]"
.LeftFooter = "&[Date] - &[Time]"
.CenterFooter = ""
.RightFooter = "Page &P / &N"
End With
sheetIndex = sheetIndex + 1
Wend
I found a solution that seems to work for replacing text. For whatever reason, in the macro, you need to include the header/footer format character codes in order for it to work properly.
This code worked to replace existing header text with new information:
Sub test()
Dim sht As Worksheet
Set sht = Worksheets(1)
sht.PageSetup.LeftHeader = "&L left text"
sht.PageSetup.CenterHeader = "&C center Text"
sht.PageSetup.RightHeader = "&R right text"
End Sub
Without the &L, &C, and &R codes before the text, I could not get it to work.
Some interesting behavior I found is that if you use the following code:
.CenterHeader = "&L some text"
it will actually put the some text in the LeftHeader position. This led me to believe that the formatting codes were very important.
The line Application.PrintCommunication = False (which is added by the macro recorder) before doing PageSetup screws up the formating via VBA.
If your code has got this line in it, try removing it. That solved my problem with setting the header and footer via VBA.
I've read StackOverflow for years and this is the first time I've actually been able to post a solution ... hope it helps someone!! Also, you need to remember, I am a CPA not a programmer ;-)
I am reading some values from the ActiveSheet to populate the header. The application is a tax election that will be sent with a tax return so it must have the taxpayer's name and social security number at the top.
Sub PrintElection()
' Print preview the MTM Election
If Range("Tax_Year").Value = Range("First_MTM_year").Value Then
ActiveSheet.PageSetup.LeftHeader = Format(Worksheets("Election").Range("Taxpayer_Name").Value)
ActiveSheet.PageSetup.RightHeader = Format(Worksheets("Election").Range("Taxpayer_SSN").Value)
ActiveWindow.SelectedSheets.PrintPreview
Else
MsgBox "The 'Effective For Tax Year' date must EQUAL the 'First MTM year' date", vbOKOnly, "Check Years"
Sheets("Roadmap").Select
Range("First_MTM_year").Select
End If
End Sub
It checks to see if the Mark-to-Market election year is the same as the election form then formats the election page.
I split the sheet print setup into 2 loops. First loop with Application.PrintCommunication = False I run the non-header/footer setup. I then set Application.PrintCommunication = True and run the header/footer setup in a second loop. Appears to run faster than in XL2003, and applies the header/footer correctly. Until MS fixes this bug, that works fine for me.