"Indirect" reference a combobox in a loop - excel

I have this problem that my excel crash whenever I try to run my code.
I do believe I have a solution but I don't know how to execute it.
I have this code:
If (AnswerGame1A <> "") And (AnswerGame1B <> "") Then
Score1A.Visible = False
Score1B.Visible = False
Resultlist1.Visible = False
SubmitGame1.Visible = False
Dash1.Visible = False
GameLabel1.Visible = True
GameLabel1.Left = 36
End If
If (AnswerGame2A <> "") And (AnswerGame2B <> "") Then
Score2A.Visible = False
Score2B.Visible = False
Resultlist2.Visible = False
SubmitGame2.Visible = False
Dash2.Visible = False
GameLabel2.Visible = True
GameLabel2.Left = 36
End If
And this continues for another 51 times.
If I remove this code, the file does not chrash, My idea is to write a loop instead.
something like this, but this doesn't work.
INFO: all these names are controls within a multipage, that is within a userform. It is comboboxes, labels, commandbuttons and textboxes. The code run when the userform initialize.
For i = 1 to 51
If (Indirect("AnswerGame" & i & "A") <> "") And (Indirect("AnswerGame" & i & "B") <> "") Then
Indirect("Score" & i & "A").Visible = False
Indirect("Score" & i & "B").Visible = False
Indirect("Resultlist" & i).Visible = False
Indirect("SubmitGame" & i).Visible = False
Indirect("Dash" & i).Visible = False
Indirect("GameLabel" & i).Visible = True
Indirect("GameLabel" & i).Left = 36
End If
Next i
Do you think this could help excel from not crashing? and how can I fix the code to work?

Supposing that your combo boxes are of sheet ActiveX type, try the next code, please:
Sub testAvoitManyIterationsCombo()
Dim sh As Worksheet, i As Long
Set sh = ActiveSheet ' use here your necessary sheet
For i = 1 To 51
If sh.OLEObjects("AnswerGame" & i & "A").Object.Value <> "" And sh.OLEObjects("AnswerGame" & i & "B").Object.Value <> "" Then
sh.Shapes("Score" & i & "A").Visible = False
sh.Shapes("Score" & i & "B").Visible = False
sh.Shapes("Resultlist" & i).Visible = False
sh.Shapes("SubmitGame" & i).Visible = False
sh.Shapes("Dash" & i).Visible = False
sh.Shapes("GameLabel" & i).Visible = True
sh.Shapes("GameLabel" & i).left = 36
End If
Next i
End Sub

and if they are not activeX this should get you on track:
Option Explicit
Private Sub UserForm_Click()
Dim i As Long, str As String
For i = 1 To 10
str = "AnswerGame" & i & "A"
If Me.Controls(str).Value = "" Then
Score1A.Visible = False
End If
Next i
End Sub

My solution that works for my purpose. The file does not seem to crash anymore.
thank you #ceci for showing how to do it.
sorry for using "x" instead of "i", "i" is already being used elsewhere.
Dim x As Long, str1 As String, str2 As String, SCO1 As String, SCO2 As String, Res As String
Dim SubmitG As String, Da As String, GameL As String
For x = 1 To 51
str1 = "AnswerGame" & x & "A"
str2 = "AnswerGame" & x & "B"
If Me.Controls(str1) <> "" Then
If Me.Controls(str2) <> "" Then
SCO1 = "Score" & x & "A"
SCO2 = "Score" & x & "B"
Me.Controls(SCO1).Visible = False
Me.Controls(SCO2).Visible = False
Res = "Resultlist" & x
Me.Controls(Res).Visible = False
SubmitG = "SubmitGame" & x
Me.Controls(SubmitG).Visible = False
Da = "Dash" & x
Me.Controls(Da).Visible = False
GameL = "GameLabel" & x
Me.Controls(GameL).Visible = True
Me.Controls(GameL).Left = 36
End If
End If
Next x

Related

Starting at a new row for every file opened, formatting every nth row

I'm looping through a folder and grabbing data points. The code below works, but I don't know how to get it to add the new data for each workbook below. It currently just pastes over each other. I tried to use i as an integer and count the number of folders and command to add 5 rows for each folder but my loop cancels out the next loop somehow. not to mention i don't know how to make it add for the next workbook. So I just need it to open the workbook, grab this data, close the workbook, open the next one, grab the same information and just put that right below what the previous workbook did.
My formatting simply needs to grab the copy range and copy the exact same range down to the last row.
Sub loopwb()
'Dim fc As Integer
'Dim sc As Range
fn = dir("C:\Users\user\Desktop\folder\*xlsx")
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Set wb = ThisWorkbook
Set ws = wb.Worksheets("List")
'Set sc = ws.Range("B11")
Do Until Len(fn) = 0
'Debug.Print fn
Set nwb = Workbooks.Open("C:\Users\user\Desktop\folder\" & fn)
Set nws = nwb.Worksheets("sht1")
ws.Range("B10").Value2 = "text"
ws.Range("B11").Value2 = nws.Range("A4").Value2
'change b11 to sc to initiate variable sequence
ws.Range("C11").Value2 = nws.Range("J6").Value2
ws.Range("H11").Value2 = nws.Range("P17").Value2
ws.Range("I11").Value2 = nws.Range("S17").Value2
ws.Range("K11").Value2 = nws.Range("S18").Value2
ws.Range("L11").Value2 = ", WAL"
ws.Range("M11").Value2 = nws.Range("L13").Value2
ws.Range("B12").Value2 = Chr(149) & " " & "text"
ws.Range("J11").Value2 = "text " & (nws.Range("E13").Value2 * 100) & " text:"
ws.Range("C12").Value2 = nws.Range("C16").Value2
ws.Range("H14").Value2 = Chr(149) & " " & "text:"
ws.Range("I14").Value2 = nws.Range("H36").Value2
ws.Range("B13").Value2 = Chr(149) & " " & "text:"
ws.Range("C13").Value2 = nws.Range("C20").Value2
ws.Range("B14").Value2 = Chr(149) & " " & "text:"
ws.Range("C14").Value2 = nws.Range("C14").Value2
ws.Range("H13").Value2 = Chr(149) & " " & "text:"
ws.Range("I13").Value2 = nws.Range("C17").Value2
If nws.Range("S10") = "text" Then
ws.Range("B15").Value2 = Chr(149) & " " & "text"
Else
ws.Range("B15").Value2 = Chr(149) & " " & "text"
End If
ws.Range("B16").Value2 = Chr(149) & " " & "text: " & nws.Range("S9").Value2
ws.Range("H16").Value2 = Chr(149) & " " & "text:"
ws.Range("I16").Value2 = nws.Range("S19").Value2
ws.Range("H15").Value2 = Chr(149) & " " & "text:"
ws.Range("I15").Value2 = nws.Range("H34").Value2
ws.Range("H12").Value2 = Chr(149) & " " & "text " & nws.Range("S11").Value2
nwb.Close savechanges:=False
fn = dir
Loop
Call format
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Sub format()
Dim cr As Range
Dim hr As Range
Dim lr As Long
Dim i As Integer
Set ws = ThisWorkbook.Worksheets("List")
With ws
Columns("B:M").EntireColumn.AutoFit
.Range("B11:M11").Font.Bold = True
.Range("B11:M11").Interior.Color = RGB(0, 48, 87)
.Range("B11:M11").Font.Color = RGB(255, 255, 255)
.Range("B16").Font.Bold = True
.Range("B15").Font.Bold = True
.Range("C12").NumberFormat = "#.000%"
.Range("C12").HorizontalAlignment = xlLeft
.Range("C16").Font.Bold = True
.Range("C16").HorizontalAlignment = xlLeft
.Range("K11").NumberFormat = "#.000%"
.Range("M11").NumberFormat = "General"
.Range("I14").NumberFormat = "#"
.Range("I14").HorizontalAlignment = xlLeft
.Range("I16").NumberFormat = "#.000%"
.Range("I15").NumberFormat = "$#,#"
.Range("I15").HorizontalAlignment = xlLeft
.Range("I13").HorizontalAlignment = xlLeft
.Range("I13").NumberFormat = "#0.000%"
Columns("D:E").ColumnWidth = 4
.Range("B10:M10").Font.Bold = True
.Range("B10:M10").Interior.Color = RGB(91, 160, 220)
.Range("B10:M10").Font.Color = RGB(255, 255, 255)
Set cr = .Range("B11:M16")
Set hr = .Range("B10:M10")
lr = .Range("B" & .Rows.count).End(xlUp).Row
'cr.Copy
' For i = 11 To lr Step 6
' PasteSpecial Paste:=xlPasteFormats
' Next i
End With
End Sub

VBA Dynamic Range VLOOKUP

I'm new to VBA and need get some help with a VLOOKUP?
I keep getting Compile error for Expected: end of statement
This is the line that is giving me problems.
I added the & sign after (row_number) and am now getting a run-time error '9': Subscript out of range error.
Sheets("WIP Count").Range("G" & (row_number)).Formula = "=VLOOKUP(C" & (row_number) & ",PRISM!L:T,8,FALSE)"
Here is the rest of the code.
Sub CommandButton1_Click()
q1_answer = Sheets("Tracker").Range("F8")
q2_answer = Sheets("Tracker").Range("F9")
q3_answer = Sheets("Tracker").Range("F10")
q4_answer = Sheets("Tracker").Range("F11")
If q1_answer = "" Then
MsgBox "Fill in Name"
Exit Sub
End If
If q2_answer = "" Then
MsgBox "Fill in Serial Number"
Exit Sub
End If
If q3_answer = "" Then
MsgBox "Fill in Part Number"
Exit Sub
End If
If q4_answer = "" Then
MsgBox "Fill in Quantity"
Exit Sub
End If
row_number = 1
Do
DoEvents
row_number = row_number + 1
item_in_review = Sheets("WIP_Count").Range("A" & row_number)
Loop Until item_in_review = ""
last_transaction_id = Sheets("WIP_Count").Range("A" & (row_number - 1))
Dim next_transaction_id As Integer
next_transaction_id = last_transaction_id + 1
Sheets("WIP_Count").Range("A" & (row_number)) = next_transaction_id
Sheets("WIP_Count").Range("B" & (row_number)) = q1_answer
Sheets("WIP_Count").Range("C" & (row_number)) = q2_answer
Sheets("WIP_Count").Range("D" & (row_number)) = q3_answer
Sheets("WIP_Count").Range("E" & (row_number)) = q4_answer
Sheets("WIP_Count").Range("F" & (row_number)).Value = Date
Sheets("WIP Count").Range("G" & (row_number)).Formula = "=VLOOKUP(C" & (row_number) & ",PRISM!L:T,8,FALSE)"
Sheets("Tracker").Range("F8") = ""
Sheets("Tracker").Range("F9") = ""
Sheets("Tracker").Range("F10") = ""
Sheets("Tracker").Range("F11") = ""
MsgBox "Done"
End Sub

VBA PivotTable error when updating table in a loop

I'm having one issue to perform a loop for 1 pivot table on excel file:
I just want to change the model2 from IJto CV
For i = 7 To 11
ActiveSheet.PivotTables("Tabela
dinâmica1").PivotFields("MODEL2").CurrentPage _
= "(All)"
With ActiveSheet.PivotTables("Tabela dinâmica1").PivotFields("MODEL2")
.PivotItems("CV").Visible = False
.PivotItems("IJ").Visible = True
.PivotItems("(blank)").Visible = False
End With
cel4 = "AV" & i
cel3 = "AX" & i
Worksheets("DDTZ C").Range("AZ" & i).Formula = "=Iferror(IF(" & cel4 &
"="""","""",VLookup(" & cel3 & ", AT:AV, 3, False)),"""")"
ActiveSheet.PivotTables("Tabela
dinâmica1").PivotFields("MODEL2").CurrentPage _
= "(All)"
With ActiveSheet.PivotTables("Tabela dinâmica1").PivotFields("MODEL2")
.PivotItems("CV").Visible = True
.PivotItems("IJ").Visible = False
.PivotItems("(blank)").Visible = False
End With
Worksheets("DDTZ C").Range("BA" & i).Value = "=Iferror(IF(" & cel4 &
"="""","""",VLookup(" & cel3 & ", AT:AV, 3, False)),"""")"
Next i
This loop has worked perfectly on first loop, however, when it start the second loop i = 8, an error appears to me, I have checked the script, and the problem is related to the followed part:
ActiveSheet.PivotTables("Tabela
dinâmica1").PivotFields("MODEL2").CurrentPage _
= "(All)"
With ActiveSheet.PivotTables("Tabela dinâmica1").PivotFields("MODEL2")
.PivotItems("CV").Visible = False
.PivotItems("IJ").Visible = True
.PivotItems("(blank)").Visible = False
End With
I cannot understand why I'm having a problem with that, since it works fine on the first loop i = 7
Anyone can help with that issue?
Thanks in advance
Try the code below.
Note: I've debugged only the PivotTable section, not the formula.
Dim PvtTbl As PivotTable
' set the Pivot Table into a variable
Set PvtTbl = ActiveSheet.PivotTables("Tabela dinâmica1")
Dim i As Long
For i = 7 To 11
With PvtTbl
With .PivotFields("MODEL2")
.ClearAllFilters
.PivotItems("CV").Visible = False
.PivotItems("(blank)").Visible = False
End With
cel4 = "AV" & i
cel3 = "AX" & i
' === Not debugging your formula part ===
Worksheets("DDTZ C").Range("AZ" & i).Formula = "=Iferror(IF(" & cel4 &
"="""","""",VLookup(" & cel3 & ", AT:AV, 3, False)),"""")"
With .PivotFields("MODEL2")
.ClearAllFilters
.PivotItems("IJ").Visible = False
.PivotItems("(blank)").Visible = False
End With
' === Not debugging your formula part ===
Worksheets("DDTZ C").Range("BA" & i).Value = "=Iferror(IF(" & cel4 &
"="""","""",VLookup(" & cel3 & ", AT:AV, 3, False)),"""")"
End With
Next i

excel 2010 vba error calling module

In the below excel 2010 vba all the text files are opened and read by the loop and then a call to a module that is in the same sheet is made. However I am getting an Argument not optional' error on that line (Call CreateXLSXFiles`). I need some expert help in fixing this as I can not figure it out. Thank you :)
VBA
'CREATE REPORT '
MsgBox ("Please click ok to generate analysis reports, vbOKOnly")
Dim myDir As String, fn As String
myDir = "C:\Users\cmccabe\Desktop\EmArray\"
fn = Dir(myDir & "*.txt")
Do While fn <> ""
CreateXLSXFiles myDir & fn
fn = Dir
Loop
Call CreateXLSXFiles
Module
Sub CreateXLSXFiles(fn As String)
' PARSE TEXT FILE AND CREATE XLSX REPORT '
Dim txt As String, m As Object, n As Long, fp As String
Dim i As Long, x, temp, ub As Long, myList
myList = Array("Display Name", "Medical Record", "Date of Birth", _
"Order Date", "Gender", "Barcode", "Sample", "Build", _
"SpikeIn", "Location", "Control Gender", "Quality")
fp = "C:\Users\cmccabe\Desktop\EmArray\"
With Worksheets(1)
.Cells.Clear
.Name = CreateObject("Scripting.FileSystemObject").GetBaseName(fn)
On Error Resume Next
n = FileLen(fn)
If Err Then
MsgBox "Something wrong with " & fn
Exit Sub
End If
On Error GoTo 0
n = 0
txt = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
With CreateObject("VBScript.RegExp")
.Global = True: .MultiLine = True
For i = 0 To UBound(myList)
.Pattern = "^#(" & myList(i) & " = (.*))"
If .Test(txt) Then
n = n + 1
Sheets(1).Cells(n, 1).Resize(, 2).Value = _
Array(.Execute(txt)(0).submatches(0), .Execute(txt)(0).submatches(1))
End If
Next
.Pattern = "^[^#\r\n](.*[\r\n]+.+)+"
x = Split(.Execute(txt)(0), vbCrLf)
.Pattern = "(\t| {2,})"
temp = Split(.Replace(x(0), Chr(2)), Chr(2))
n = n + 1
For i = 0 To UBound(temp)
Sheets(1).Cells(n, i + 1).Value = temp(i)
Next
ub = UBound(temp)
.Pattern = "((\t| {2,})| (?=(\d|"")))"
For i = 1 To UBound(x)
temp = Split(.Replace(x(i), Chr(2)), Chr(2))
n = n + 1
Sheets(1).Cells(n, 1).Resize(, ub).Value = temp
Next
End With
.Copy
Application.DisplayAlerts = False
With ActiveSheet
.Columns.AutoFit
.Range("B1:B12").ClearContents
End With
ActiveWorkbook.SaveAs Filename:=fp & .Name, _
FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close False
End Sub
The method CreateXLSXFiles takes a String as input :
Sub CreateXLSXFiles(fn As String)
However, you're calling it without passing any string:
Call CreateXLSXFiles
In order to make it work, you need to pass the needed fn (that I guess it means "file name") :
Call CreateXLSXFiles(fn)
or with the newest syntax, simply:
CreateXLSXFiles fn

Graphs with various Y values and one X values in Excel VBA

This is the code i use to create a graph which searches for .csv {created using excel application} file in the path specified. It plots the column 'B' { Y axis } against column 'C' {X-axis}.. I want to one more column 'A' to my Y axis keeping column 'C' as the X axis.. How can i do that???
here is the code...
Sub Draw_Graph()
Dim strPath As String
Dim strFile As String
Dim strChart As String
Dim i As Integer
Dim j As Integer
strPath = "C:\PortableRvR\report\"
strFile = Dir(strPath & "*.csv")
i = 1
Do While strFile <> ""
With ActiveWorkbook.Worksheets.Add
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Destination:=.Range("A1"))
Parent.Name = Replace(strFile, ".csv", "")
TextFileParseType = xlDelimited
TextFileTextQualifier = xlTextQualifierDoubleQuote
TextFileConsecutiveDelimiter = False
TextFileTabDelimiter = False
TextFileSemicolonDelimiter = False
TextFileCommaDelimiter = True
TextFileSpaceDelimiter = False
TextFileColumnDataTypes = Array(1)
TextFileTrailingMinusNumbers = True
Refresh BackgroundQuery:=False
Files(i) = .Parent.Name
i = i + 1
End With
End With
strFile = Dir
Loop
numOfFiles = i - 1
chartName = "Chart 1"
For j = 1 To numOfFiles
strFile = Files(j)
Sheets(strFile).Select
Plot_y = Range("B1", Selection.End(xlDown)).Rows.Count
Plot_x = Range("C1", Selection.End(xlDown)).Rows.Count
Sheets("GraphDisplay").Select
If j = 1 Then ActiveSheet.ChartObjects(chartName).Activate
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(j).Name = strFile
ActiveChart.SeriesCollection(j).XValues = Sheets(strFile).Range("C1:C" & Plot_x)
ActiveChart.SeriesCollection(j).Values = Sheets(strFile).Range("B1:B" & Plot_y)
ActiveChart.SeriesCollection(j).MarkerStyle = -4142
ActiveChart.SeriesCollection(j).Smooth = False
Next j
ActiveSheet.ChartObjects(chartName).Activate
ActiveChart.Axes(xlValue).DisplayUnit = xlMillions
ActiveChart.Axes(xlValue).HasDisplayUnitLabel = False
End Sub
you can add 2 series for every file (j and j+1 inside for j = 1 to 2*numOfFiles step 2) and repeat everything for j+1 series except:
ActiveChart.SeriesCollection(j).Values = Sheets(strFile).Range("A1:A" & Plot_y)
ActiveChart.SeriesCollection(j+1).Values = Sheets(strFile).Range("B1:B" & Plot_y)
Not for points
I was planning to post this as a comment (and hence do not select this as an answer. All credit to #Aprillion) but the comment would not have formatted the code as this post would have done.
Whenever you add a series as Aprillion mentioned you have to also add one more line. I just tested this with small piece of data and it works.
'<~~ You have to call this everytime you add a new series
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).Values = "=Sheet1!$B$1:$B$6"
'<~~ You have to call this everytime you add a new series
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(2).Values = "=Sheet1!$A$1:$A$6"
Also since there is a huge difference between your Series 1 Data and Series 2 data (as per the snapshot), the 2nd series will be very close to X Axis.
Hope this is what you wanted?
FOLLOWUP
Is this what you are trying?
Dim files(1 To 20) As String
Dim numOfFiles As Integer
Dim chartName As String, shName as String
Sub Time_Graph()
Dim strPath As String, strFile As String, strChart As String
Dim i As Long, j As Long, n As Long
strPath = "C:\PortableRvR\report\"
strFile = Dir(strPath & "*.csv")
i = 1
Do While strFile <> ""
With ActiveWorkbook.Worksheets.Add
shName = strFile
ActiveSheet.Name = Replace(shName, ".csv", "")
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Destination:=.Range("A1"))
.Name = Replace(strFile, ".csv", "")
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
files(i) = .Parent.Name
i = i + 1
End With
End With
strFile = Dir
Loop
numOfFiles = i - 1
chartName = "Chart 1"
For j = 1 To numOfFiles
If n = 0 Then n = j Else n = n + 2
strFile = files(j)
Sheets(strFile).Select
Plot_y = Range("B1", Selection.End(xlDown)).Rows.Count
Plot_x = Range("C1", Selection.End(xlDown)).Rows.Count
Sheets("GraphDisplay").Select
If j = 1 Then ActiveSheet.ChartObjects(chartName).Activate
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(n).Name = strFile & " - Col B Values"
ActiveChart.SeriesCollection(n).XValues = "=" & strFile & "!$C$1:$C$" & Plot_x
ActiveChart.SeriesCollection(n).Values = "=" & strFile & "!$B$1:$B$" & Plot_y
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(n + 1).Name = strFile & " - Col A Values"
ActiveChart.SeriesCollection(n + 1).XValues = "=" & strFile & "!$C$1:$C$" & Plot_x
ActiveChart.SeriesCollection(n + 1).Values = "=" & strFile & "!$A$1:$A$" & Plot_y
ActiveChart.SeriesCollection(j).MarkerStyle = -4142
ActiveChart.SeriesCollection(j).Smooth = False
ActiveChart.SeriesCollection(n + 1).MarkerStyle = -4142
ActiveChart.SeriesCollection(n + 1).Smooth = False
Next j
ActiveSheet.ChartObjects(chartName).Activate
ActiveChart.Axes(xlValue).DisplayUnit = xlMillions
ActiveChart.Axes(xlValue).HasDisplayUnitLabel = False
End Sub

Resources