Как читать строки в листе в массив пользовательских классов в VBA? Vba строку в массив


string - Как преобразовать простую строку в байт-массив в VBA?

Мне нужно преобразовать простую строку в массив байтов, используя excel VBA. Затем этот массив байтов используется как тело запроса.

Как я могу это сделать?

Спасибо.

задан Ubalo 16 июня '09 в 1:26 источник поделиться

Matthew ответил, как преобразовать в ANSI, но если вы хотите, чтобы полученный массив байтов все еще представлял исходную строку Unicode, вы просто назначили его напрямую:

Public Sub Main() Dim b() As Byte Dim s As String s = "Whatever" b = s 'Assign Unicode string to bytes.' s = b 'Works in reverse, too!' Debug.Print s End Sub

Вот и все. В итоге вы получите 16-элементный байт-массив, каждая последующая пара, описывающая один символ Юникода.

источник поделиться ' a bit of an example ' had some strings down column G ' nothing in columns "F" or "H" so that current works ' Think about it.. there are many many columns ' so leave blank columns on each side of setsof dats ' then currentregion works ... IFF no blank rows in the data ' ' problem to solve some text was Fred3 John2 Blue3 ' others were Bert 3 Green 2 ... which was the require format ' the ASC char 1 ..255 are the odd or even ' numbered bytes if array is 1 based or 0 based ' Private Sub CommandButton1_Click() Dim RV$, Ra As Range, Ri&, AL%, WSA() As Byte Dim Ci%, WS$, LV As Byte Set Ra = Range("g8").CurrentRegion For Ri = 1 To Ra.Rows.Count WSA = CStr(Ra(Ri, 1).value) AL = UBound(WSA) LV = WSA(AL - 1) ' last char byte value If LV > 47 And LV < 58 Then ' 0 to 9 If WSA(AL - 3) <> 32 Then ' no space " " ReDim Preserve WSA(AL + 2) ' allow 1 more char WSA(AL - 3) = 32 ' put in space WSA(AL - 1) = LV ' return char WS = WSA ' back to a string Ra(Ri, 1) = WS ' back to the cell End If End If Next Ri End Sub ' of course the normal VBAcommands Instr len Mid replace & ' would do the job ... but my brain is lazy and needed some exercise ответ дан Harry S 17 дек. '16 в 9:34 источник поделиться

qaru.site

Практическое руководство. Преобразование строки (String) в массив символов в Visual Basic

  • 07/20/2015
  • Время чтения: 2 мин
  • Соавторы

В этой статье

Иногда бывает удобно иметь данные о символов в строки и позиции этих символов, например при анализе строки.Sometimes it is useful to have data about the characters in your string and the positions of those characters within your string, such as when you are parsing a string. В этом примере показано, как можно получить массив символов в строку путем вызова строки ToCharArray метод.This example shows how you can get an array of the characters in a string by calling the string's ToCharArray method.

ПримерExample

В этом примере показано, как разбить строку в Char массива и как разбить строку на String массив знаков Юникода.This example demonstrates how to split a string into a Char array, and how to split a string into a String array of its Unicode text characters. Это различие связано что Юникода может состоять из двух или более Char символов (например, суррогатная пара или несамостоятельных последовательность символов).The reason for this distinction is that Unicode text characters can be composed of two or more Char characters (such as a surrogate pair or a combining character sequence). Дополнительные сведения см. в разделе TextElementEnumerator и The Unicode Standard.For more information, see TextElementEnumerator and The Unicode Standard.

Dim testString1 As String = "ABC" ' Create an array containing "A", "B", and "C". Dim charArray() As Char = testString1.ToCharArray

ПримерExample

Сложнее для разбиения строки на знаков Юникода, но это необходимо, если вам нужна информация об визуальное представление строки.It is more difficult to split a string into its Unicode text characters, but this is necessary if you need information about the visual representation of a string. В этом примере используется SubstringByTextElements метод для получения сведений о текстовых символов Юникода, составляющих строку.This example uses the SubstringByTextElements method to get information about the Unicode text characters that make up a string.

' This string is made up of a surrogate pair (high surrogate ' U+D800 and low surrogate U+DC00) and a combining character ' sequence (the letter "a" with the combining grave accent). Dim testString2 As String = ChrW(&HD800) & ChrW(&HDC00) & "a" & ChrW(&h400) ' Create and initialize a StringInfo object for the string. Dim si As New System.Globalization.StringInfo(testString2) ' Create and populate the array. Dim unicodeTestArray(si.LengthInTextElements) As String For i As Integer = 0 To si.LengthInTextElements - 1 unicodeTestArray(i) = si.SubstringByTextElements(i, 1) Next

См. такжеSee Also

Chars[Int32]System.Globalization.StringInfoПрактическое руководство. Доступ к символам в строкахHow to: Access Characters in StringsПреобразование между строками и другими типами данных в Visual BasicConverting Between Strings and Other Data Types in Visual BasicСтрокиStrings

docs.microsoft.com

vba - Как читать строки в листе в массив пользовательских классов в VBA?

Скажите, что ваша таблица "Sheet1" выглядит примерно так:

Когда вы открываете редактор Visual Basic ALT + F11, вам нужно щелкнуть правой кнопкой мыши проект VBA и вставить 2 модуля: один стандартный Module1 и один класс.

Переименуйте модуль класса в Student и заполните его

Public Id As Long Public Name As String Public Math As Long Public Science As Long Public English As Long Public History As Long Public Function GetAverage() GetAverage = (Math + Science + English + History) / 4 End Function

И в Module1

Sub Main() Dim students As New Collection ' collection to store all students Dim cell As Range ' iterator Dim person As Student ' for each cell in column A For Each cell In Sheets(1).Range("A2:A" & Range("A" & Rows.Count).End(xlUp).Row) ' create a new student object Set person = New Student ' fill the data person.Id = cell person.Name = cell.Offset(0, 1) person.Math = cell.Offset(0, 2) person.Science = cell.Offset(0, 3) person.English = cell.Offset(0, 4) person.History = cell.Offset(0, 5) ' add the student to the collection of students students.Add person Next ' open Immediate Window CTRL + G or VIEW -> Immediate Window Dim s As Student For Each s In students Debug.Print "ID: " & s.Id & vbTab & "Name: " & s.Name, "Math: " & s.Math, "Science: " & s.Science, "English: " & s.English, "History: " & s.History, "Avg: " & s.getAverage() Next End Sub

Теперь, если вы запустите F5 свой макрос и проверите свое окно Immediate, у вас будут все данные из вашей электронной таблицы, загруженные программно в коллекцию;

* Примечание: Я задокументировал это с некоторыми дополнительными деталями

ответ дан user2140173 20 авг. '14 в 10:22

qaru.site

Добавление в массив в VBA со строками в качестве индекса MS Excel онлайн

Это будет обрабатывать произвольное количество «ключей» (q1, q2 и т. Д.),

Sub Tester() 'needs a reference to microsoft scripting runtime Dim d As New Scripting.dictionary Dim c As Range Dim arrP, arrE Dim q, v, tmpV, tmpP, tmpArr, uB Dim i As Long, n As Long Dim k For Each c In Selection.Cells tmpV = Trim(c.Value) If InStr(tmpV, "=") > 0 Then arrP = Split(tmpV, "|") 'split on pipe For i = LBound(arrP) To UBound(arrP) tmpP = arrP(i) If InStr(tmpP, "=") > 0 Then q = Trim(Split(tmpP, "=")(0)) v = Trim(Split(tmpP, "=")(1)) If IsNumeric(v) Then If Not d.exists(q) Then d.Add q, Array(v) Else tmpArr = d(q) 'get dict value into temp array uB = UBound(tmpArr) + 1 ReDim Preserve tmpArr(0 To uB) 'extend array tmpArr(uB) = v d(q) = tmpArr 'put back into dict End If End If End If Next End If 'cell has at least one "=" Next c 'dump the dictionary to the immediate pane For Each k In d.keys Debug.Print k, Join(d(k), ",") Next k End Sub

Это сложно, но это можно сделать. Я тестировал это в excel на основе ввода вашей ячейки, помещая их в A1 и A2:

q1 = 1 | q2 = 3.2 | q3 = 5.6 q1 = 1.8 | q3 = 2.1 | q5 = 1.4

Я собрал макрос в Excel под названием «Looper», который использует два цикла для циклического перемещения по ячейкам в столбце A, разделить их на «|» и найдите каждое числовое значение, преобразуйте его в double и поместите его в соответствующий массив.

Private Sub Looper() ''Loop Variables Dim i, k As Integer Dim MoveDown As String ''Variables to manipulate the string Dim Selecter As String Dim TotalCell As String Dim Splitter As Variant Dim strIncrement As String ''Array variables and counters Dim q1(50) As Double Dim q2(50) As Double Dim q3(50) As Double Dim qv1, qv2, qv3 As Integer ''Variables for finding the number in each increment Dim Equals As Integer Dim strNumber As String Dim dblNumber As Double ''Set the array counters to 0 qv1 = 0 qv2 = 0 qv3 = 0 i = 0 Do Until MoveDown = "DONE" Selector = "A" + Replace(Str(i), " ", "") If Range(Selector).Value = "" Then MoveDown = "DONE" Else TotalCell = Range(Selector).Value Splitter = Split(TotalCell, "|") For k = LBound(Splitter) To UBound(Splitter) ''strIncrement holds the data in between each | strIncrement = Splitter(k) ''Remove any spaces strIncrement = Replace(strIncrement, " ", "") ''Equals shows the location of the number (length of string - loc of =) Equals = Len(strIncrement) - InStr(1, strIncrement, "=") strNumber = Right(strIncrement, Equals) dblNumber = CDbl(strNumber) ''Check for the array name and then add the data to the corresponding array If InStr(1, strIncrement, "q1") > 0 Then q1(qv1) = dblNumber qv1 = qv1 + 1 Else If InStr(1, strIncrement, "q2") > 0 Then q2(qv2) = dblNumber qv2 = qv2 + 1 Else If InStr(1, strIncrement, "q3") > 0 Then q3(qv3) = dblNumber qv3 = qv3 + 1 End If End If End If Next End If i = i + 1 Loop End Sub

Я смог успешно добавить данные в массивы, поэтому оттуда должно быть просто идти, чтобы вычислить средства и т. Д.

excel.bilee.com

Сравнение двух массивов в VBA и добавление строк MS Excel онлайн

так как я довольно новичок в VBA, мне нужна помощь с частью моего кода, которая должна сравнивать два массива, отсортированные по возрастанию, и если значение в любом из массивов отсутствует, то предполагается, что строка добавляется в соответствующую таблицу и заполните отсутствующее значение нулевым значением в ячейке рядом с ним. Это то, что у меня есть до сих пор:

With ActiveSheet LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row End With For I = 3 To LastRow If Cells(I, 1) > Cells(I, 6) Then LastRow = LastRow + 1 With Range("A" & I & ":C" & I) .Select .Insert Shift:=xlDown End With Range("A" & I) = Cells(I, 6) Cells(I, 2).Value = 0 ElseIf Cells(I, 1).Value < Cells(I, 6).Value Then With Range("F" & I & ":H" & I) .Select .Insert Shift:=xlDown End With Range("F" & I) = Cells(I, 1) Cells(I, 7).Value = 0 Else End If Next i

Проблема с этим кодом, помимо его неэффективности (что не является проблемой, поскольку оба массива очень малы) заключается в том, что LastRow: a) изменяется с каждой добавленной строкой; b) учитывает LastRow в массиве1, поэтому, если array2 больше, 't идти полностью вниз, c) если ячейка пуста, кажется, что добавить строку с пустой ячейкой в ​​соответствующий массив, даже если я добавлю

If Not IsEmpty (Cells(i, 1)) And IsEmpty(Cells(i, 6)) Then 'next i

Я знаю, что решение, вероятно, связано с определением обоих массивов и использованием LBound для Ubound, но я не мог опустить голову. Большое спасибо за помощь!

EDIT: Последняя строка кажется теперь исправленной, однако я все еще не могу как-то пропускать пустые ячейки и ячейку в последней, которая содержит текст «Grand Total» внутри и, следовательно, не сортируется в отличие от остальной части диапазона. У кого-нибудь есть идеи, как обойти это? Вот как выглядит код:

CurrentRow = 3 Do While CurrentRow <= LastRow If Cells(CurrentRow, 1) > Cells(CurrentRow, 6) Then If Not Cells(CurrentRow, 6).Value = "Grand Total" Or IsEmpty(Cells(CurrentRow, 6).Value) Then With Range("A" & CurrentRow & ":C" & CurrentRow) .Select .Insert Shift:=xlDown End With Range("A" & CurrentRow) = Cells(CurrentRow, 6) Cells(CurrentRow, 2).Value = 0 End If ElseIf Cells(CurrentRow, 6) > Cells(CurrentRow, 1) Then If Not Cells(CurrentRow, 1).Value = "Grand Total" Or IsEmpty(Cells(CurrentRow, 1).Value) Then With Range("F" & CurrentRow & ":H" & CurrentRow) .Select .Insert Shift:=xlDown End With Range("F" & CurrentRow) = Cells(CurrentRow, 1) Cells(CurrentRow, 7).Value = 0 End If Else End If With ActiveSheet LastRow = .UsedRange.Rows(.UsedRange.Rows.Count).Row End With CurrentRow = CurrentRow + 1 Debug.Print CurrentRow Loop

ИЗМЕНИТЬ 2: Я понял это наконец! Я добавил еще одно условие, чтобы добавить строку в противоположную таблицу, если она найдет значение «Grand Total». Не нужно беспокоиться о пустых ячейках!

CurrentRow = 3 Do While CurrentRow <= LastRow If Cells(CurrentRow, 1) > Cells(CurrentRow, 6) Then If Cells(CurrentRow, 6).Value = "Grand Total" Then With Range("F" & CurrentRow & ":H" & CurrentRow) .Select .Insert Shift:=xlDown End With Range("F" & CurrentRow) = Cells(CurrentRow, 1) Cells(CurrentRow, 7).Value = 0 Else With Range("A" & CurrentRow & ":C" & CurrentRow) .Select .Insert Shift:=xlDown End With Range("A" & CurrentRow) = Cells(CurrentRow, 6) Cells(CurrentRow, 2).Value = 0 End If ElseIf Cells(CurrentRow, 6) > Cells(CurrentRow, 1) Then If Cells(CurrentRow, 1).Value = "Grand Total" Then With Range("A" & CurrentRow & ":C" & CurrentRow) .Select .Insert Shift:=xlDown End With Range("A" & CurrentRow) = Cells(CurrentRow, 6) Cells(CurrentRow, 2).Value = 0 Else With Range("F" & CurrentRow & ":H" & CurrentRow) .Select .Insert Shift:=xlDown End With Range("F" & CurrentRow) = Cells(CurrentRow, 1) Cells(CurrentRow, 7).Value = 0 End If Else End If With ActiveSheet LastRow = .UsedRange.Rows(.UsedRange.Rows.Count).Row End With CurrentRow = CurrentRow + 1 Debug.Print CurrentRow Loop
Solutions Collecting From Web of "Сравнение двух массивов в VBA и добавление строк"

хороший аккуратный вопрос для перемен! Вот мои мысли о первых двух частях:

a) с циклом for, начальные условия (Lastrow в этом случае) считываются только при запуске цикла, поэтому, если вы измените Lastrow во время цикла, цикл будет выполняться только до исходного значения.

чтобы обойти это, вы могли бы реструктурировать его как цикл while. используя общий пример:

Sub loop_for() Dim intLoop As Integer Dim intEnd As Integer intEnd = 3 For intLoop = 1 To intEnd 'this is fixed as soon as is triggered Debug.Print intLoop If intLoop = 2 Then intEnd = 4 'this has no effect on loop Next intLoop 'output is 1,2,3 End Sub

В.С.

Sub loop_while() Dim intLoop As Integer Dim intEnd As Integer intLoop = 1 intEnd = 3 Do While intLoop <= intEnd Debug.Print intLoop intLoop = intLoop + 1 If intLoop = 2 Then intEnd = 4 Loop 'output is 1,2,3,4 End Sub

б) почему бы просто не оценить и то, и другое?

Sub lastrow() Dim lastrow As Long Dim lastrow1 As Long Dim lastrow2 As Long lastrow1 = ActiveSheet.Cells(.Rows.Count, "A").End(xlUp).Row lastrow2 = ActiveSheet.Cells(.Rows.Count, "F").End(xlUp).Row lastrow = Application.Max(lastrow1, lastrow2) End Sub

c) закончилось здесь, надеюсь, кто-то другой может помочь.

excel.bilee.com