Excel VBA Can't get selected value from combobox - vba

I've been reading numerous posts here in the forum regarding my problem but I'm afraid I'm still doing something awfully wrong.
Overtaken today by the button rage, I admit to some confusion.
I have been trying to put a simple userform combobox (frmWorkers) which includes a combobox (cbWorkers) and linked to a defined rowSource (Workers), the click of which will simply get me the value of that worker's name. (Thank you Ann!)
The combobox opens just fine but refuses to click and there I'm stopped.
I'm now receiving a 'compile error, for each control variable must be variant or object' at **for each WorkerName...
Private Sub UserForm_Initialize()
Dim wsControl As Worksheet
Dim Workers As Range
Dim WorkerName As String
Set Workers = Range("Workers")
**For Each WorkerName In Range("Workers")
If WorkerName = Not Nothing Then
Me.cbWorkers.AddItem WorkerName
End If
End sub
I've also been trying to get it alternatively from ThisWorkbook, but I'm getting a 'run-time error 91, object variable or with block variable not set', right after **WorkerName.
Sub UsingTheScriptingRunTimeLibrary()
Dim fso As Scripting.FileSystemObject
Dim fileMakoret As Scripting.File, filePayroll As Scripting.File
Dim WorkerName As String, folderPath As String, NewFolderPath As String
Dim wsControl As Worksheet
Dim newWbMaskoret As Workbook, wbPayroll As Workbook, wbControl As Workbook
Dim cbWorkers As ComboBox
Set wbControl = ActiveWorkbook
Set wsControl = wbControl.Sheets("Control")
**WorkerName = cbWorkers.Value
WorkerName = Worksheets("wsControl").OLEObjects("cbWorkers").Object.Value
Your help is much appreciated.

Does the object frmWorkerName have a Value property? What type of object is it?
I think the problem with your second code snippet is that you define cbWorkers, but you never assign a value to it. It therefore has a value of Nothing ("null" in other languages.)
When you then try to access the value of cbWorkers, you get an error, since there is no object there to access a property for.
ETA: About your second problem: here's the code:
Dim Workers As Range
Dim WorkerName As String
Set Workers = Range("Workers")
For Each WorkerName In Range("Workers")
You're getting the error because, to do a For Each loop, the type of the variable WorkerName needs to be compatible with the type of the collection Range("Workers") that you're iterating through.
The error message tells you: you need to make WorkerName an Object or a Variant if you're going to use it in a For Each loop with that collection.
I doubt, by the way, that the elements in an Excel Range object are simple strings. They are probably Cell objects, or objects of a type with a similar name. You will need to cast WorkerName to type Cell (or whatever) within the loop, and then access its Text or Value property.

Related

Unable to create a Dropdownlist that contains key and values in Excel

I'm having trouble creating a dropdownlist that contains a name and a value for each column.
What I want to achieve is to use the dropdownlist that shows a bunch of names, but I want those names to have a
value, so that I can use it (value) in macro.
For exmple, when I select a name called "Joe" it will consists of the value 25 and will
be outputted as 25.
I've Googled around for some tutorials, but most of it wasn't useful. I've pasted the the img. I want to create a drown from this
Bakers name and value. But have no clue to how I can make this possible.
Some examples or tips would be great! I would love to hear from you.
Here is the macro code:
Sub findValue()
Dim s As String
Dim value As Integer
Dim namesList As Range
Set namesList = Range("G3:G8") 'here you have to specify your range with names
s = InputBox("Enter the name: ")
'now you find the entered value (held in s variable) and get the value of a cell which
'is right to cell found (Offset function, then applied Value property)
value = namesList.Find(s).Offset(0, 1).Value
MsgBox "Found value is " & value
'save found value into the file
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = fso.CreateTextFile(yourPath) 'don't forget to enter full path to the
'text file here!!
oFile.WriteLine value
oFile.Close
Set fso = Nothing
Set oFile = Nothing
End Sub
Now, the value is stored under value variable, you can do what you want with it :)

Defining a variable as a range - VB.NET

I think I'm losing my mind - how do you declare a variable as a string and then set it equal to a range in an Excel workbook in VB.NET? In VBA this was easy:
Dim SQL as string
SQL = ActiveWorkbook.Sheets("MySheet").Range("SQL")
If I try do something like this in VB.NET (in Visual Studio 2015), first I can't find Activeworkbook. Second, if I try Excel.Range("SQL"), I get an error saying that 'Range' is an interface type and cannot be used as an expression. Also, it doesn't look like the Range data type exists either. Surely this functionality exists in VB.NET, right?
Thanks for the help!
To work on Excel since VB.NET, first you must add the reference to your Project :
Microsoft.Office.Interop
To Add a Reference :
In Solution Explorer, right-click on the References node and choose Add Reference.
Import the Reference in your code :
Imports Microsoft.Office.Interop
Try to use this code :
Dim AppExcel As New Excel.Application 'Create a new Excel Application
Dim workbook As Excel.Workbook = AppExcel.Workbooks.Add() 'Create a new workbook
Dim sheet As Excel.Worksheet = workbook.Sheets("Sheet1") ' Create variable a Sheet, Sheet1 must be in WorkBook
'Work with range
Dim cellRange1 As Excel.Range = sheet.Range("A1") 'Range with text address
cellRange1.Value = "Text in Cell A1"
Dim cellRange2 As Excel.Range = sheet.Cells(2, 2) 'Range("B2:B2") with index; Cells(N°Row,N°Col)
cellRange2.Value = "Text in Cell B2"
Dim tableRange3 As Excel.Range = sheet.Range("A1:F4") 'Range with text address
Dim tableRange4 As Excel.Range = sheet.Range(sheet.Cells(1, 1), sheet.Cells(4, 6)) 'Range("A1:F4") with index; Cells(N°Row,N°Col)
AppExcel.Visible = True 'To display the workbook
Code without variable sheet
Dim AppExcel as New Excel.Application
Dim workbook As Excel.Workbook = AppExcel.Workbooks.Add()
'Range
Dim cellrange1 as Excel.Range = AppExcel.ActiveWorkbook.Sheets("Feuil1").Range("A1")
You would need to start from your application object. Suppose that's AppExcel:
Dim AppExcel As New Excel.Application
From there, you could do:
Dim cellrange1 as Excel.Range = AppExcel.ActiveWorkbook.Sheets("MySheet").Range("SQL")
Because you've declared cellrange1 as a Range it can't be set to Range("SQL").Value.
Value returns an object which is the value contained in that Range.
That's so wordy. To put it (maybe) more clearly, Range("SQL") returns a Range. Range("SQL").Value returns an object.
If you want to get the value, that would be cellrange1.Value, or perhaps cellrange1.Text. Assuming that the range contains some sort of SQL, I'd go with Text.
An unfortunate aspect of Excel interop programming is that many properties return objects rather than strongly-typed values. For example, the object returned by Range.Text is always going to be a string, but the property still returns an object. That means that Visual Studio intellisense will often not tell you what type a property returns. You'll need to look up properties and functions in the documentation to really know what they return.

Set xWorkb = New workbook not working, ActiveX error

I have some code below, It works like a charm but I'm curious about some things.
Why can't I make a Set xWorkb = new Workbook statement? Instead I use the Dim xWorkb as new Workbook, which works. But I've learned (hopefully correct) that using the new statement within a Dim is bad practice, and that you should create the object seperately. So why doesn't it work? I get a ActiveX component can't create object error, but the xWorkb is still being created later as an object right due to the new statement in the Dim section? Makes me confusing.
Why can't I use the excel.application.workbooks when defining variable xApp? Is it because I have to specify a workbook and can't just leave the workbooks empty like that? I get a type mismatch error when I'm trying to change excel.application to excel.application.workbooks.
Sub tester()
Dim xWorkb As New Workbook
Dim xApp As Excel.Application: Set xApp = New Excel.Application
Dim xFiles_target() As Variant
Dim file_path As String
xFiles_target = Array("Bella.xls", "Fizz.xls", "Milo.xls", "Jake.xls")
file_path = Dir("C:\Users\hans\Desktop\")
Do While Len(file_path) > 0
Debug.Print file_path
If UBound(Filter(xFiles_target, file_path)) >= 0 Then
Debug.Print "found " & file_path
Set xWorkb = xApp.Workbooks.Open("C:\Users\hans\Desktop\" & file_path)
xApp.ActiveSheet.Cells(2, 2) = "tester"
xWorkb.Save
xWorkb.Close
End If
file_path = Dir
Loop
End Sub
You cannot create new workbooks with New because workbooks are coupled with Application and must be created with Workbooks.Add or Workbooks.Open.
Dim xWorkb as new Workbook does not work - it appears to work because you don't access xWorkb between declaring it and assigning it with Workbooks.Open. If you did, you would get the same ActiveX component can't create object error.
The error is because Excel.Workbook does not have any public constructors.
You cannot define a variable as excel.application.workbooks because that is not a type. It is a property named Workbooks, of type Excel.Workbooks, that belongs to an object named Application of type Excel.Application.
You can declare the variable as Excel.Workbooks, but you probably don't want to, because you will need to create an Excel.Application to use it anyway.

VISIO count shapes in container

I'm pretty rusty with VBA and I was hoping someone could point me in the right direction, or help me out. What I'm trying to do is run a macro that will cycle through each active container on my sheet, and then count the number of shapes within that container. Then I'd like to update a field in the shape data for the container with the number of shapes.
This is what I have so far:
Public Sub countContainers()
Dim vsoPage As Visio.Page
Dim vsoDocument As Visio.Document
Dim vsoDocuments As Visio.Documents
Dim vsoPages As Visio.Pages
Dim vsoContainerShape As Visio.Shape
Dim containerId As Variant
For Each containerId In vsoPage.GetContainers(visContainerIncludeNested)
Set vsoContainerShape = vsoPage.Shapes.ItemFromID(containerId)
Debug.Print vsoContainerShape.NameU
Next
End Sub
The error I get is Object Variable or With Block variable not set
Any ideas?
The error is because you have declared the vsoPage but you never assigned it to any page in your document.
Add a line such as this to initialize it and the error goes away:
Set vsoPage = ActivePage

Using a Variable to Dim a Worksheet

I have a sheet with one cell that is = the name of a folder that I want to dim as a variable. what I want to do is set that cell = the filename variable. It will probably be easier to look at my code. I am currently getting the "object required error on my "set Input 1" and my way to set the variable is presumably wrong as well
Dim WbkA As Workbook
Dim Input1 as string
Set Input1 = Workbooks.Open(Filename:="G:\Reporting\ReportCompare.xls").worksheets("Sheet4").Range("A4").Value
Set wbkA = Workbooks.Open(FileName:"Input1")
You try to assign a reference of an object with the keyword Set to a data type (String).
Remove the keyword Set and it's gonna be okay.
The code needs to be reordered slightly in order to breakout the steps.
Get the file path and name from the workbook and store it as a string
variable (Input1).
Open the file using the value stored in the string variable (Input1).
Set a reference to the open file as an object variable (WbkA).
Listed below is the code
Sub test()
Dim Input1 As String
Dim WbkA As Workbook
Input1 = Worksheets("Sheet4").Range("A4").Value 'Get the path and file name
Workbooks.Open Filename:=Input1 'Open the file
Set WbkA = ActiveWorkbook 'Set the reference to the workbook
MsgBox WbkA.Name 'Show the name value from the object.
End Sub