I would like to reuse vSheetNamesTemp array.
It's collecting sheets with q* but I want to use it for other sheets like w*.
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swDrawing = swModel
Dim vSheetNamesTemp As Variant
vSheetNamesTemp = swDrawing.GetSheetNames
removed = 0
For i = 0 To UBound(vSheetNamesTemp)
vSheetNamesTemp(i - removed) = vSheetNamesTemp(i)
SheetName = vSheetNamesTemp(i)
If Not SheetName Like "q*" Then
removed = removed + 1
End If
Next i
If (UBound(vSheetNamesTemp) - removed) >= 0 Then
ReDim Preserve vSheetNamesTemp(0 To (UBound(vSheetNamesTemp) - removed))
vSheetNames = vSheetNamesTemp
End If
End Sub
Try the next approach, please:
Create a variable on top of the module (declarations side):
Private vSheetNames As Variant
Copy your transformed Sub:
Sub main()
Dim arrCriteria As Variant, El As Variant
'Please, appropriately declare the used variables. I do not use Solidworks
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swDrawing = swModel
vSheetNames = swDrawing.GetSheetNames
arrCriteria = Split("q*,w*,x*", ",") 'use here as many criteria you need
For Each El In arrCriteria
If UBound(vSheetNames) >= 0 Then
removeSh vSheetNames, El
End If
Next
End Sub
In the same module, copy the next function:
Private Function removeSh(vSheetNamesTemp As Variant, strCriteria As String)
Dim removed As Long, i As Long
removed = 0
For i = 0 To UBound(vSheetNamesTemp)
vSheetNamesTemp(i - removed) = vSheetNamesTemp(i)
If Not vSheetNamesTemp(i) Like strCriteria Then
removed = removed + 1
End If
Next i
If (UBound(vSheetNamesTemp) - removed) >= 0 Then
ReDim Preserve vSheetNamesTemp(0 To (UBound(vSheetNamesTemp) - removed))
vSheetNames = vSheetNamesTemp
End If
End Function
The code is not tested, but it should work, I think. Please test it and send some feedback.
Related
I have 2 arrays taken from 2 ranges in a sheet. I'm trying to create a third array that contains only the values contained in array 1 that are missing in array 2 (I found this code online).
Array 2´s size will vary and depends on this code:
Dim iListaIncompleta() As Variant
Dim iCountLI As Long
Dim iElementLI As Long
iCountLI = Range("B1").End(xlDown).Row
ReDim iListaIncompleta(iCountLI)
For iElementLI = 1 To iCountLI
iListaIncompleta(iElementLI - 1) = Cells(iElementLI, 2).Value
Next iElementLI
and Array 1's size is always from A1:A7, and I use this code to create it:
Dim iListaCompleta() As Variant
Dim iElementLC As Long
iListaCompleta = Range("A1:A7")
This is the original code I found online to extract missing values:
Dim v1 As Variant, v2 As Variant, v3 As Variant
Dim coll As Collection
Dim i As Long
'Original Arrays from the code:
v1 = Array("Bob", "Alice", "Thor", "Anna") 'Complete list
v2 = Array("Bob", "Thor") 'Incomplete list
Set coll = New Collection
For i = LBound(v1) To UBound(v1)
If v1(i) <> 0 Then
coll.Add v1(i), v1(i) 'Does not add value if it's 0
End If
Next i
For i = LBound(v2) To UBound(v2)
On Error Resume Next
coll.Add v2(i), v2(i)
If Err.Number <> 0 Then
coll.Remove v2(i)
End If
If coll.Exists(v2(i)) Then
coll.Remove v2(i)
End If
On Error GoTo 0
Next i
ReDim v3(LBound(v1) To (coll.Count) - 1)
For i = LBound(v3) To UBound(v3)
v3(i) = coll(i + 1) 'Collections are 1-based
Debug.Print v3(i)
Next i
End Sub
However, this code has arrays defined like this:
v1 = Array("Bob", "Alice", "Thor", "Anna")
And the actual arrays I wanna use are defined differently (as you can see in the first two pieces of code). When I try to run the code with them, it displays
Error 9: Subscript out of range.
The code works well as it originally is, but when I try to use MY arrays, it's when I get this error.
Obviously, I've tried it changing the names of the variables (v1 and v2) to my own 2 arrays (iListaCompleta and iListaIncompleta), and still doesn't work.
Any ideas??
Thank you in advance!
Here's a function that can be used to compare arrays of any dimension size to pull out differences and put only the differences in a one-dimensional array:
Public Function ArrayDifference(ByVal arg_Array1 As Variant, ByVal arg_array2 As Variant) As Variant
If Not IsArray(arg_Array1) Or Not IsArray(arg_array2) Then Exit Function 'Arguments provided were not arrays
Dim vElement As Variant
Dim hDifference As Object: Set hDifference = CreateObject("Scripting.Dictionary")
For Each vElement In arg_Array1
If Not hDifference.exists(vElement) Then hDifference.Add vElement, vElement
Next vElement
For Each vElement In arg_array2
If hDifference.exists(vElement) Then
hDifference.Remove vElement
Else
hDifference.Add vElement, vElement
End If
Next vElement
ArrayDifference = hDifference.Keys
End Function
Here's how you would call the function to compare two different arrays. It also includes how to populate the initial arrays using your provided setup:
Sub arrays()
Dim ws As Worksheet: Set ws = ActiveWorkbook.ActiveSheet
Dim rList1 As Range: Set rList1 = ws.Range("A1", ws.Cells(ws.Rows.Count, "A").End(xlUp))
Dim rList2 As Range: Set rList2 = ws.Range("B1", ws.Cells(ws.Rows.Count, "B").End(xlUp))
Dim aList1 As Variant
If rList1.Cells.Count = 1 Then
ReDim aList1(1 To 1, 1 To 1)
aList1(1, 1) = rList1.Value
Else
aList1 = rList1.Value
End If
Dim aList2 As Variant
If rList2.Cells.Count = 1 Then
ReDim aList2(1 To 1, 1 To 1)
aList2(1, 1) = rList2.Value
Else
aList2 = rList2.Value
End If
Dim aList3 As Variant
aList3 = ArrayDifference(aList1, aList2)
MsgBox Join(aList3, Chr(10))
End Sub
Assigning word document lines of text to an array to then print into an excel column. I want to print each item in array to it's own cell.
Currently, all the items are storying correctly into the array, but it's only printing the first item over and over Action
Code:
Option Explicit
Sub ParaCopy()
Dim wApp As Word.Application
Dim wDoc As Word.Document
Set wApp = CreateObject("Word.Application")
Set wDoc = wApp.Documents.Open("J:\Data Dictionary.docx", ReadOnly:=True)
Dim wPara As Word.Paragraph
Dim arr() As Variant
Dim i As Long
i = 0
For Each wPara In wDoc.Paragraphs
If wPara.Range.Words.Count > 1 Then
ReDim Preserve arr(i)
arr(i) = wPara.Range
End If
i = i + 1
Next wPara
For i = LBound(arr) To UBound(arr)
[a1].Resize(UBound(arr) + 1) = arr
Next i
End Sub
EDIT: Need to separate each block of text separated by a space (outlined in blue) to this
Create a 2D array with one column and load that:
Option Explicit
Sub ParaCopy()
Dim wApp As Word.Application
Dim wDoc As Word.Document
Set wApp = CreateObject("Word.Application")
Set wDoc = wApp.Documents.Open("J:\Data Dictionary.docx", ReadOnly:=True)
Dim wPara As Word.Paragraph
Dim arr() As Variant
ReDim arr(1 To wDoc.Paragraphs.Count, 1 To 1)
Dim i As Long
i = 1
For Each wPara In wDoc.Paragraphs
If wPara.Range.Words.Count > 1 Then
arr(i, 1) = wPara.Range
i = i + 1
End If
Next wPara
[a1].Resize(UBound(arr) + 1) = arr
End Sub
Copy Word Paragraphs to Excel Cells Using an Array
The number of rows of the array is wDoc.Paragraphs.Count which may differ from r (the 'actual count') hence you have to use r with Resize, and not wDoc.Paragraphs.Count or UBound(Data, 1).
Don't forget to Close the Document and Quit the App.
The first solution is early-bound and needs the library reference. When using it, just use
Set wApp = New Word.Application.
The second solution is late-bound and doesn't need the library reference. Also, it has been 'stripped off' the document and application variables (not necessary, you can declare them As Object).
Option Explicit
' e.g. Tools>References>Microsoft Word 16.0 Object Library
Sub ParaCopy()
Const FilePath As String = "J:\Data Dictionary.docx"
Dim wApp As Word.Application: Set wApp = Set wApp = New Word.Application
Dim wDoc As Word.Document: Set wDoc = wApp.Documents.Open(FilePath, , True)
Dim Data As Variant: ReDim Data(1 To wDoc.Paragraphs.Count, 1 To 1)
Dim wPara As Word.Paragraph
Dim r As Long
For Each wPara In wDoc.Paragraphs
If wPara.Range.Words.Count > 1 Then
r = r + 1
Data(r, 1) = wPara.Range
End If
Next wPara
wDoc.Close False
wApp.Quit
[a1].Resize(r) = Data
End Sub
Sub ParaCopyNoReference()
Const FilePath As String = "J:\Data Dictionary.docx"
With CreateObject("Word.Application")
With .Documents.Open(FilePath, , True)
Dim Data As Variant: ReDim Data(1 To .Paragraphs.Count, 1 To 1)
Dim wPara As Object
Dim r As Long
For Each wPara In .Paragraphs
If wPara.Range.Words.Count > 1 Then
r = r + 1
Data(r, 1) = wPara.Range
End If
Next wPara
.Close False
End With
.Quit
End With
[a1].Resize(r) = Data
End Sub
I have a function that loads certain data from a dynamic table into an array. The function works fine, when I check the local window I get the correct data. Also when I call the data from a sub, everything seems to work fine till I write the array to a new sheet, then I only get the first record repeatedly.
This is my code:
Function LoadData() As String()
Dim rng2 As Range, intJaNein As Integer, rngZelle As Range, X As Integer, cntAnzahl As Integer
Dim strAusgabe() As String 'R?ckgabe Array
intJaNein = 1
X = 0
Set rng2 = Range("tblMaschinen[DisplayList]")
cntAnzahl = WorksheetFunction.CountIfs(rng, m_intListIndex, rng2, intJaNein)
ReDim strAusgabe(cntAnzahl)
For Each rngZelle In rng2.Cells
If rngZelle.Offset(, -2).value = 0 And _
rngZelle.value = 1 And _
X <= cntAnzahl Then
strAusgabe(X) = rngZelle.Offset(, -1).value
X = X + 1
End If
Next rngZelle
LoadData = strAusgabe
End Function
Sub Test()
Dim sht As Worksheet, rng As Range, arr() As String
If ThisWorkbook.Worksheets("Loeschen") Is Nothing Then
Set sht = ActiveWorkbook.Worksheets.Add
sht.Name = "Loeschen"
End If
Set rng = Range("A1:A19")
arr = cls.LoadData
rng.value = arr
End Sub
This is the locals output when getting to the last row of code (rng.value = arr)
And this is what appears in my worksheet.
I have a loop, and I want to put the result into array.
Here is my loop.
For i = 1 To bill
a = rs("CT08_Tarikh") 'from db
cutiumum = Array(a) 'and this is how I declare array
rs.MoveNext
Next
rs.Close
Set rs = Nothing
End If
and after that, i will pass the variable to another function:
tarikh = NetWorkdays(dateFrom, dateTo, cutiumum)
Public Function NetWorkdays(dtStartDate, dtEndDate, arrHolidays)
but, when I try to do some loop for arrHolidays inside the function NetWorkdays, it only return 1 data (not all from the cutiumum).
What do you think is my mistake?
Update
I'm already using
dim arrRecordset
arrRecordset = rs.GetRows()
but I got an error inside the function
Public Function NetWorkdays(dtStartDate, dtEndDate, arrHolidays)
Dim lngDays
Dim lngSaturdays
Dim lngSundays
Dim lngHolidays
Dim lngAdjustment
Dim dtTest
Dim i, x
lngDays = DateDiff("d", dtStartDate, dtEndDate)
lngSundays = DateDiff("ww", dtStartDate, dtEndDate, vbSunday)
lngSaturdays = DateDiff("w", IIf(Weekday(dtStartDate, vbSunday) = vbSaturday, dtStartDate, dtStartDate - Weekday(dtStartDate, vbSunday)), dtEndDate)
For x = LBound(arrHolidays) To UBound(arrHolidays)
For i = 0 To lngDays
dtTest = DateAdd("d", i, dtStartDate)
'error in line here: Subscript out of range: 'arrHolidays'
If arrHolidays(x) = dtTest And Weekday(dtTest) <> 1 And Weekday(dtTest) <> 7 Then
lngHolidays = lngHolidays + 1
End If
Next
Next
If Weekday(dtStartDate, vbSunday) = vbSunday Or Weekday(dtStartDate, vbSunday) = vbSaturday Then
lngAdjustment = 0
Else
lngAdjustment = 1
End If
NetWorkdays = lngDays - lngSundays - lngSaturdays - lngHolidays + lngAdjustment
End Function
Try this:
dim arrRecordset
arrRecordset = rs.GetRows()
The getRows() method will transform a recordset into a two dimensional array in one go:
https://www.w3schools.com/asp/met_rs_getrows.asp
I'm running into an odd issue. I have 2 Userform, at first Userform2 was inside Userform1, but I wasn't able to make it run. After that I made that a Sub in my Module call Userform2 after other once Userform1 is done.
The problem is the Userform2 is a Multiselect Listbox, and I save each selection in an array and when the Userform2 unloads the array seems to be empty.
I have checked for hours many errors like: I have no explicit option on, but the code is pretty short and I have looked for the array within my code and it only appears on the exact parts I wanted it to be.
Neither the public array as variant was a problem, because it is outside the Userform and in the original Module.
I'm from Chile so some variables have names in Spanish and my English might not be so good, I'll do my best to explain my self.
Here is the code:
Global lenarrv
Global Arrver
Global BoxPMData
Global anno
Global PMDATAarray
Global LenPMDArray
Public varfamilia As Variant
Public pampm As Variant
Sub AbrirMaestro(ByVal anno As Variant)
Application.ScreenUpdating = False
UserForm1.Show
UserForm2.Show
Dim Arrver() As Variant
Dim lenarrv As Long
contentosrcontento = 1
lenarrv = UBound(pampm)
For tt = 0 To lenarrv - 1
ReDim Arrver(contentosrcontento)
Arrver(contentosrcontento) = pampm(tt)
contentosrcontento = contentosrcontento + 1
Next tt
lenarrv = UBound(Arrver)
Inputbox_PMDATA anno
End Sub
Here comes the Userforms:
Private Sub UserForm_Activate()
Me.StartUpPosition = 1
Me.Left = Application.Left + Application.Width - Me.Width - 400
End Sub
Private Sub UserForm_Initialize()
Dim listaitems As Variant
Workbooks("MAESTROS.xlsx").Activate
numerofilas = Workbooks("MAESTROS.xlsx").Sheets("VERTICALES").Cells(2, 1).End(xlDown).Row
listaitems = Workbooks("MAESTROS.xlsx").Sheets("VERTICALES").Range("A2:A" & numerofilas)
listaitems = Application.WorksheetFunction.Transpose(listaitems)
For h = 1 To numerofilas - 1
ListBox1.AddItem listaitems(h)
Next h
Workbooks("MAESTROS.xlsx").Close False
End Sub
Public Sub CommandButton1_Click()
Dim i As Integer
Dim count As Integer
count = 1
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) = True Then
ReDim pampm(count)
pampm(i) = ListBox1.List(i)
count = count + 1
End If
Next i
Unload UserForm2
End Sub
Here is UserForm1 :
Private Sub UserForm_Activate()
Me.StartUpPosition = 1
Me.Left = Application.Left + Application.Width - Me.Width - 400
End Sub
Private Sub UserForm_Initialize()
Dim ListItems As Variant
MsgBox ("Elegir el archivo MAESTRO")
Master = Application.GetOpenFilename(MultiSelect:=False)
isBool = VarType(Master) = vbBoolean
If isBool Then If Not Master Then End
Application.ScreenUpdating = False
Set abrirlibro = Workbooks.Open(Master)
numrows = abrirlibro.Worksheets("MASTERFAMILIA").Cells(2, 2).End(xlDown).Row
ListItems = abrirlibro.Worksheets("MASTERFAMILIA").Range("B2:B" & numrows)
ListItems = Application.WorksheetFunction.Transpose(ListItems)
For i = 1 To numrows - 1
ComboBox1.AddItem ListItems(i) ' populate the listbox
Next i
'abrirlibro.Close False
'Set abrirlibro = Nothing
End Sub
Public Sub CommandButton1_Click()
varfamilia = ComboBox1.value
Unload UserForm1
End Sub
I can't past the full code since there are more than 2k lines..
Any help is welcome.
Greetings!
you have to change
Public pampm As Variant
to
Public pampm() As Variant
and
ReDim pampm(count)
to
ReDim Preserve pampm(count)