Я взял диапазон ячеек из своего листа Excel, но для каждой ячейки в диапазоне я хочу добавить нить + открытие html, затем добавить ячейка 1 из диапазона, который я взял из своего листа Excel, затем добавить закрытие HTML и, наконец, перейти к ячейка 2 В диапазоне. Повторение процесса для следующей строки + открытие html + ячейка 2 + закрытие html.
Метод, который я использую в настоящее время, неверен, поскольку он каждый раз помещает ВСЕ строки, html и текущую ячейку в тело, а затем перемещается в ячейку 2 в диапазоне!
Вот мой код:
Sub Email_Figures_Click()
'Lets dim the things we need
Dim CDO_Mail As Object
Dim CDO_Config As Object
Dim SMTP_Config As Variant
Dim strSubject As String
Dim strFrom As String
Dim strTo As String
Dim strCc As String
Dim strBcc As String
Dim myRng As Range
'To begin with, we want a clean Range, meaning nothing inside
Set myRng = Nothing
'So I am setting the cells I wish to use from the Excel Sheet Monthly Figures
Set myRng = Sheets("Monthly Figures").Range("B5,B6,B8,B9,B10,B11,B12,B13,B15,B17,B18,B19,B20,B22,B23,B25").SpecialCells(xlCellTypeVisible)
'Error Handling message, just incase
If myRng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "Please correct and try again.", vbOKOnly
Exit Sub
End If
html_text = _
"<font style='size:22px;weight:bold;'>**HIDDEN** Monthly Figures</font></br></br>"
'NOTE: UPDATED THE LOOP AND HTML BELOW FOR BODY
For Each Row In myRng.Rows
For Each cell In Row.Cells
html_text = html_text & _
"<font style='size:18px;'>Month: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br></br>"
html_text = html_text & _
"<font style='size:14px;'>Purchases Total: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br>"
html_text = html_text & _
"Purchases Count: <font style='weight:bold;'>" & _
cell.Text & "</font></br></br>"
html_text = html_text & _
"Invoices Total: <font style='weight:bold;'>" & _
cell.Text & "</font></br>"
html_text = html_text & _
"Paid Invoices Total: <font style='weight:bold;color:green;'>" & _
cell.Text & _
"</font></br>"
html_text = html_text & _
"Unpaid Invoices Total: <font style='weight:bold;color:red;'>" & _
cell.Text & _
"</font></br>"
html_text = html_text & _
"Sales Invoices Count: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br>"
html_text = html_text & _
"Paid Sales Invoices Count: <font style='weight:bold;color:green;'>" & _
cell.Text & _
"</font></br>"
html_text = html_text & _
"Unpaid Sales Invoices Count: <font style='weight:bold;color:red;'>" & _
cell.Text & _
"</font></br></br>"
html_text = html_text & _
"Tax Receipts Total: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br></br>"
html_text = html_text & _
"Float Money Starting Balance: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br>"
html_text = html_text & _
"Float Money Current Balance: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br>"
html_text = html_text & _
"Float Money In: <font style='weight:bold;color:green;'>" & _
cell.Text & _
"</font></br>"
html_text = html_text & _
"Float Money Out: <font style='weight:bold;color:red;'>" & _
cell.Text & _
"</font></br></br>"
html_text = html_text & _
"Cash Sales Total: <font style='weight:bold;color:red;'>" & _
cell.Text & _
"</font></br>"
html_text = html_text & _
"Cash Sales Count: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br></br>"
html_text = html_text & _
"Months Evaluation: <font style='weight:bold;'>" & _
cell.Text & _
"</font></font></br>"
Next cell
Next Row
'Some more sexy error handling
Set CDO_Mail = CreateObject("CDO.Message")
On Error GoTo Error_Handling
'Sets our SMTP settings so we can send emails....and stuff.
Set CDO_Config = CreateObject("CDO.Configuration")
CDO_Config.Load -1
Set SMTP_Config = CDO_Config.Fields
With SMTP_Config
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "**HIDDEN**"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "HIDDEN"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "HIDDEN"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
.Update
End With
'This is where I made myself a cup of tea because I was getting tired! :D
With CDO_Mail
Set .Configuration = CDO_Config
End With
'And finally this is the email subject, to, from, body, cc, and any bcc
CDO_Mail.Subject = "HIDDEN"
CDO_Mail.From = "HIDDEN"
CDO_Mail.To = "HIDDEN"
CDO_Mail.HTMLBody = html_text
CDO_Mail.CC = ""
CDO_Mail.BCC = ""
'Send the message
CDO_Mail.Send
'Error handling
Error_Handling:
If Err.Description <> "" Then MsgBox Err.Description
End Sub
Sub Print_Figures_Click()
ActiveWindow.SelectedSheets.PrintOut ' print
End Sub
(Примечание: Этот код был обновлен 18/07/2018, чтобы показать использование измененного For Each Row In myRng.Rows и HTML, но все еще требует дополнительных поправок.)
Это «может» быть возможным частичным решением, но я не уверен, как его правильно реализовать:
' Declare an array with 18 elements including 0 as the first.
Dim my_body_text(17) As String
' Assign values to each element.
my_body_text(0) = _
"<font style='size:22px;weight:bold;'>**HIDDEN** Monthly Figures</font></br></br>"
my_body_text(1) = my_body_text(0) & _
"<font style='size:18px;'>Month: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br></br>"
my_body_text(2) = my_body_text(1) & _
"<font style='size:14px;'>Purchases Total: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br>"
my_body_text(3) = my_body_text(2) & _
"Purchases Count: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br></br>"
my_body_text(4) = my_body_text(3) & _
"Invoices Total: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br>"
my_body_text(5) = my_body_text(4) & _
"Paid Invoices Total: <font style='weight:bold;color:green;'>" & _
cell.Text & _
"</font></br>"
my_body_text(6) = my_body_text(5) & _
"Unpaid Invoices Total: <font style='weight:bold;color:red;'>" & _
cell.Text & _
"</font></br>"
my_body_text(7) = my_body_text(6) & _
"Sales Invoices Count: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br>"
my_body_text(8) = my_body_text(7) & _
"Paid Sales Invoices Count: <font style='weight:bold;color:green;'>" & _
cell.Text & _
"</font></br>"
my_body_text(9) = my_body_text(8) & _
"Unpaid Sales Invoices Count: <font style='weight:bold;color:red;'>" & _
cell.Text & _
"</font></br></br>"
my_body_text(10) = my_body_text(9) & _
"Tax Receipts Total: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br></br>"
my_body_text(11) = my_body_text(10) & _
"Float Money Starting Balance: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br>"
my_body_text(12) = my_body_text(11) & _
"Float Money Current Balance: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br>"
my_body_text(13) = my_body_text(12) & _
"Float Money In: <font style='weight:bold;color:green;'>" & _
cell.Text & _
"</font></br>"
my_body_text(14) = my_body_text(13) & _
"Float Money Out: <font style='weight:bold;color:red;'>" & _
cell.Text & _
"</font></br></br>"
my_body_text(15) = my_body_text(14) & _
"Cash Sales Total: <font style='weight:bold;color:red;'>" & _
cell.Text & _
"</font></br>"
my_body_text(16) = my_body_text(15) & _
"Cash Sales Count: <font style='weight:bold;'>" & _
cell.Text & _
"</font></br></br>"
my_body_text(17) = my_body_text(16) & _
"Months Evaluation: <font style='weight:bold;'>" & _
cell.Text & _
"</font></font></br>"
' Create a 10-element integer array.
Dim i As Integer
' Add info & increase by 1 each time.
For i = 0 To 17
'
' ADD THE CELL INTO STRING HERE SOMEHOW!
'
'
my_body_text(i) = my_body_text(i) + 1
Next i
Любая помощь приветствуется!
Обновление используемого кода по состоянию на 19.07.2018:
Эта версия правильно отправляет электронное письмо и правильно отправляет каждый из Cell.Text, но по какой-то причине она не отправляет теги <font> или строки в тегах <font>.
Например: вместо того, чтобы помещать полную строку "Tax Receipts Total: <font style='weight:bold;'>" & Cell.Text из Case 10 в html_text, он помещает: Month: из Case 1 без тегов <font> в каждый раз, а затем добавляет правильно обновленный Cell.Text.
Это почти работает ... Можете ли вы посоветовать, что мне не хватает?
(И есть ли способ скопировать также символ валюты? Поскольку для символов валюты, кроме $ или £, отображается только вопросительный знак. Я знаю, что юникод для того, что я хочу, - это U + 0E3F. Можно ли это просто поместить в строка?)
'Begin Email button
Sub Email_Figures_Click()
'Dims the things we need
Dim CDO_Mail As Object
Dim CDO_Config As Object
Dim SMTP_Config As Variant
Dim strSubject As String
Dim strFrom As String
Dim strTo As String
Dim strCc As String
Dim strBcc As String
Dim myRng As Range
Dim CaseRange As Integer
'To begin with, we want a clean Range, meaning nothing inside
Set myRng = Nothing
'So I am setting the cells I wish to use from the Excel Sheet Monthly Figures
Set myRng = Sheets("Monthly Figures").Range("B2,B5,B6,B8,B9,B10,B11,B12,B13,B15,B17,B18,B19,B20,B22,B23,B25").SpecialCells(xlCellTypeVisible)
'Error Handling message, just incase
If myRng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "please correct and try again.", vbOKOnly
Exit Sub
End If
'Sets the email body title (inside the html_text)
html_text = "<font style='size:22px;weight:bold;'>**HIDDEN** Monthly Figures</font></br></br>"
'Defaults the CaseRange to 1
CaseRange = 1
For Each Row In myRng.Rows 'For each Row
For Each Cell In Row.Cells 'And for each cell in the Row
Select Case CaseRange 'Select a Case from our CaseRange
Case 1
html_text = html_text & "<font style='size:18px;'>Month: <font style='weight:bold;'>" & Cell.Text & "</font></br></br>"
Case 2
html_text = html_text & "<font style='size:14px;'>Purchases Total: <font style='weight:bold;'>" & Cell.Text & "</font></br>"
Case 3
html_text = html_text & "Purchases Count: <font style='weight:bold;'>" & Cell.Text & "</font></br></br>"
Case 4
html_text = html_text & "Invoices Total: <font style='weight:bold;'>" & Cell.Text & "</font></br>"
Case 5
html_text = html_text & "Paid Invoices Total: <font style='weight:bold;color:green;'>" & Cell.Text & "</font></br>"
Case 6
html_text = html_text & "Unpaid Invoices Total: <font style='weight:bold;color:red;'>" & Cell.Text & "</font></br>"
Case 7
html_text = html_text & "Sales Invoices Count: <font style='weight:bold;'>" & Cell.Text & "</font></br>"
Case 8
html_text = html_text & "Paid Sales Invoices Count: <font style='weight:bold;color:green;'>" & Cell.Text & "</font></br>"
Case 9
html_text = html_text & "Unpaid Sales Invoices Count: <font style='weight:bold;color:red;'>" & Cell.Text & "</font></br></br>"
Case 10
html_text = html_text & "Tax Receipts Total: <font style='weight:bold;'>" & Cell.Text & "</font></br></br>"
Case 11
html_text = html_text & "Float Money Starting Balance: <font style='weight:bold;'>" & Cell.Text & "</font></br>"
Case 12
html_text = html_text & "Float Money Current Balance: <font style='weight:bold;'>" & Cell.Text & "</font></br>"
Case 13
html_text = html_text & "Float Money In: <font style='weight:bold;color:green;'>" & Cell.Text & "</font></br>"
Case 14
html_text = html_text & "Float Money Out: <font style='weight:bold;color:red;'>" & Cell.Text & "</font></br></br>"
Case 15
html_text = html_text & "Cash Sales Total: <font style='weight:bold;color:red;'>" & Cell.Text & "</font></br>"
Case 16
html_text = html_text & "Months Evaluation: <font style='weight:bold;'>" & Cell.Text & "</font></font></br>"
Case Else
html_text = html_text & "Error: Cannot find the Case Cell Number to import to email"
End Select
Next Cell 'Jump to the next cell and repeat the the process
Next Row ' Jump to next Row and repeat the process
'error handling
Set CDO_Mail = CreateObject("CDO.Message")
On Error GoTo Error_Handling
'Sets our SMTP settings so we can send emails
Set CDO_Config = CreateObject("CDO.Configuration")
CDO_Config.Load -1
Set SMTP_Config = CDO_Config.Fields
'Settings for sending the email
With SMTP_Config
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "**HIDDEN**"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "**HIDDEN**"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "**HIDDEN**"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
.Update
End With
'Sets the config
With CDO_Mail
Set .Configuration = CDO_Config
End With
'Defines Email Attributes
CDO_Mail.Subject = "**HIDDEN** Monthly Figures"
CDO_Mail.From = "**HIDDEN**"
CDO_Mail.To = "**HIDDEN**"
CDO_Mail.HTMLBody = html_text
CDO_Mail.CC = ""
CDO_Mail.BCC = ""
'Sends the email
CDO_Mail.Send
'Error handling and email sent successfully confirmation
Error_Handling:
If Err.Description <> "" Then MsgBox Err.Description Else MsgBox "Message sent successfully"
'End the button
End Sub
Sub Print_Figures_Click()
ActiveWindow.SelectedSheets.PrintOut ' print
End Sub
Снимок экрана ниже с выводом электронного письма
Фиктивные данные, передаваемые по электронной почте
Обновлено 20.07.2017, чтобы сделать выбор моего случая более похожим на то, что предложил @Paul
@Павел
Примечания и обновления:
HTML, связанный со стилем CSS, похоже, не работает. Например: <h3></h> и <font style='weight:bold;color:green;'></font>, они просто не хотят работать в рамках выбора случая. Мне бы пришлось использовать <b><font color='green' size='14'>. При этом он выбирает HTML-тег самый первый в первом случае Только, который используется, и применяется ко всему в html_text после этого. Несмотря на закрывающие HTML-теги!
Я не вижу никакой разницы с использованием моего 1 диапазона всех ячеек и использования ваших 2 диапазонов, 1 для заголовков и 1 для итогов. Похоже, делает то же самое. Я пробовал оба варианта, чтобы исключить этот вариант. Затем я добавил все Заголовки заголовков для каждой суммы в диапазон, так что количество ячеек диапазона теперь удвоилось.
От вашего последнего обновления до вашего ответа объясняет случаи намного больше, чем то, что я смог найти где-либо еще в Интернете, так что спасибо за это. Я изменил свои кейсы, чтобы сделать их максимально похожими на ваши.
Ниже приведен полный код на сегодняшний день:
'Begin Email button
Sub Email_Figures_Click()
'Dims the things we need
Dim CDO_Mail As Object
Dim CDO_Config As Object
Dim SMTP_Config As Variant
Dim strSubject As String
Dim strFrom As String
Dim strTo As String
Dim strCc As String
Dim strBcc As String
Dim myRng As Range
Dim CaseRange As Integer
'To begin with, we want a clean Range, meaning nothing inside
Set myRng = Nothing
'So I am setting the cells I wish to use from the Excel Sheet Monthly Figures
Set myRng = Sheets("Monthly Figures").Range("A2,B2,A5,B5,A6,B6,A8,B8,A9,B9,A10,B10,A11,B11,A12,B12,A13,B13,A15,B15,A17,B17,A18,B18,A19,B19,A20,B20,A22,B22,A23,B23,A25,B25").SpecialCells(xlCellTypeVisible)
'Error Handling message, just incase
If myRng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "please correct and try again.", vbOKOnly
Exit Sub
End If
'Sets the email body title (inside the html_text)
html_text = "<html><body><h1>**HIDDEN** Monthly Figures</h1><br><br /><br><br />"
'Defaults the CaseRange to 1
CaseRange = 1
For Each Row In myRng.Rows 'For each Row
For Each Cell In Row.Cells 'And for each cell in the Row
Select Case CaseRange
'Month Title Heading
Case 1
html_text = html_text & _
"<h2>" & _
Cell.Text & _
"</h2>"
'The Month
Case 2
html_text = html_text & _
"<h2>" & _
Cell.Text & _
"</h2>"
'All other Title Headings
Case 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33
html_text = html_text & _
"<h3>" & _
Cell.Text & _
"</h3>"
'All the Black Totals
Case 4, 6, 8, 14, 20, 22, 24, 32, 34
html_text = html_text & _
"<h3>" & _
Cell.Text & _
"</h3>"
'All the Red Totals
Case 12, 18, 28, 30
html_text = html_text & _
"<h3><font color='red'>" & _
Cell.Text & _
"</font></h3>"
'All the Green Totals
Case 10, 16, 26
html_text = html_text & _
"<h3><font color='green'>" & _
Cell.Text & _
"</font></h3>"
End Select
Next Cell 'Jump to the next cell and repeat the the process
Next Row ' Jump to next Row and repeat the process
'Close our html & body tags before adding to email
html_text = html_text & "</body></html>"
'error handling
Set CDO_Mail = CreateObject("CDO.Message")
On Error GoTo Error_Handling
'Sets our SMTP settings so we can send emails
Set CDO_Config = CreateObject("CDO.Configuration")
CDO_Config.Load -1
Set SMTP_Config = CDO_Config.Fields
'Settings for sending the email
With SMTP_Config
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "**HIDDEN**"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "**HIDDEN**"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "**HIDDEN**"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
.Update
End With
'Sets the config
With CDO_Mail
Set .Configuration = CDO_Config
End With
'Defines Email Attributes
CDO_Mail.Subject = "**HIDDEN** Monthly Figures"
CDO_Mail.From = "**HIDDEN**"
CDO_Mail.To = "**HIDDEN**"
CDO_Mail.HTMLBody = html_text
CDO_Mail.CC = ""
CDO_Mail.BCC = ""
'Sends the email
CDO_Mail.Send
'Error handling and email sent successfully confirmation
Error_Handling:
If Err.Description <> "" Then MsgBox Err.Description Else MsgBox "Message sent successfully"
'End the button
End Sub
И вот полученное электронное письмо:
Начните здесь: Циклы Excel VBA
Не работает. Я не понимал / не совсем понимал, как я работал в следующий раз, ссылка ниже проливает свет на то, что @JosephC упомянул, спасибо.
По поводу обновления: Зачем заморачиваться? Вы только что записали идеально подходящий цикл в последовательный список операторов, но каждый раз используете одну и ту же ячейку. Я бы порекомендовал вам сначала остановиться и прочитать документацию по VBA. Select Case и For To Next здесь ваши друзья. Я специально использовал For To Next, так как он дает вам порядковые номера для сравнения ...
Зачем беспокоиться? Методом проб и ошибок! Поскольку я совсем не владею VBA. В конце концов, StackOverflow - это обучение и обмен знаниями. Я пытаюсь решить этот небольшой участок почти 3 дня. Я пробовал много разных решений, которые нашел в Интернете, но, похоже, ничего не подходит для того, что я ищу. И это лишь малая часть всей функциональности книги. Я прочитаю Select Class и For To Next, а затем дам это назад. - Возможно, я вернусь: P Если мне удастся отсортировать его, я нажму, чтобы принять ваш ответ о помощи, которую вы оказали. Спасибо.
Хорошо, спасибо в отношении Select Case, мне удалось это решить, и я изменил свой код, чтобы показать это. Я также добавил обновление к исходному вопросу. Электронное письмо отправляется правильно, данные Cell.Text вводятся правильно, а строки html и до и после Cell.Text - нет. Есть ли у вас какие-либо дополнительные советы по разрешению передаваемых строк html?
Очевидно, это какой-то финансовый отчет. Есть ли в вашей электронной таблице имена, которые вы используете в электронном письме, вверху соответствующих столбцов на листе?
Я обновил свой ответ. Возможно, это будет выглядеть для вас чище. Небольшой совет - все ваши столбцы должны иметь связанные с ними заголовки для описания того, к чему относятся данные - используйте их!






Все эти утверждения Next могут вызвать у вас проблемы.
Я бы сказал, поместите заголовок статистики в ячейку выше, а затем вы можете включить это в диапазон. Оттуда это просто случай ...
Const colStart As Integer = 5: Const colEnd As Integer = 25
Const rowTitle As Integer = 2: Const rowData As Integer = 3
Dim x As Integer
Dim msg As String
For x = colStart To colEnd
If Cells(rowTitle, x) <> "" Then
msg = msg & Cells(rowTitle, x) & _
"<font style='weight:bold;size:18px;'>" & Cells(rowData, x) & "</font>"
End If
Next x
В качестве альтернативы вы можете создать список строк, которые хотите использовать, и разделить их ...
Dim strTitles() As String
strTitles = Split("List of titles,and other,things", ",")
Dim x As Integer
For x = colStart To colEnd
...
Или вы можете сохранить справочный лист для таких вещей, как заголовки, и переключаться между ними, используя метод, аналогичный упомянутому выше ...
For x = colStart To colEnd
If Worksheets(0).Cells(rowTitle, x) <> "" Then
msg = msg & Worksheets(0).Cells(rowTitle, x) & _
"<font style='weight:bold;size:18px;'>" & _
Worksheets(1).Cells(rowData, x) & _
"</font>"
End If
Next x
Еще один вариант - иметь рабочий лист для управления все ваших настроек. Например...
А затем прочтите значения из этого, чтобы получить свои значения из подходящего места ...
Dim strSht As String
Dim row As Integer, cols As Integer, x As Integer
strSheet = Worksheets("MySettings").Cells(1,1)
row = Worksheets("MySettings").Cells(2,1)
cols = Worksheets("MySettings").Cells(3,1)
For x = 4 to 3 + cols
msg = msg & _
"<strong>" & _
Worksheets("MySettings").Cells(x,1) & _
"</strong>" & _
Worksheets(strSht).Cells(row, Worksheets("MySettings").Cells(x,1))
Next x
Вы полностью упустили суть. Нет абсолютно никаких причин для цикла, если вы собираетесь независимо форматировать каждую строку таким образом.
Дизайн
Во-первых, решающее значение имеет дизайн - вы просто не хотите менять слишком много настроек шрифта. Вместо использования font-size: 22pt; weight: bold; рассмотрите возможность использования тега <h1>. Точно так же для шрифта чуть меньшего размера используйте <h2>. Для всего, что должно выделяться, используйте <strong> и используйте <em> для всего, что нужно подчеркнуть (вы можете использовать теги <b> или <i>, если хотите, так как они используют снова становясь более принятым, хотя с некоторыми это отношения любви и ненависти, хотя в вашем случай их использования будет семантически специфичным). Слишком частое изменение размера шрифта затрудняет чтение электронной почты.
Если вам нужно использовать цвет, то используйте только два - черный и другой цвет. Опять же, слишком частое изменение цвета делает его беспорядочным (ИМО). Например, финансовые разработчики, которых я знаю, обычно используют только черный и красный цвета и угадывают, какой текст обычно красный? ...
Использование Select Case
Идея Select Case заключалась в том, чтобы предел объем работы, который вам нужно было выполнить. В вашем случае это просто не сработает, если вы не измените свой дизайн. Причина, по которой я рекомендовал это, заключалась в том, чтобы попытаться помочь вам ограничить объем переформатирования, который вы собирались выполнить.
Select Case предназначен для работы с небольшим количеством опций из большего количества. Например, в вашем случае вы могли бы использовать ...
Const rowHead As Integer = theRowNumberThatHasTheHeadingsOnIt
Dim rowData As Integer, colStart, colEnd
rowData = theRowNumberThatHasTheDataOnIt
colStart = theFirstColumnInTheList
colEnd = theLastColumnInTheList
Dim msgText As String
For x = colStart To colEnd
Select Case x
Case 1
msgText = _
"<h1>" & _
Cell(x, rowData) & _
"</h1>"
Case 2
msgText = _
"<h2>" & _
Cell(x, rowData) & _
"</h2>"
Case 3, 4, 7, 10, 11, 12, 16
msgText = _
"<strong>" & _
Cell(x, rowHead) & ": " & _
"</strong>" & _
Cell(x, rowData)
Case 5, 8, 13
msgText = _
"<strong style='color: green;'>" & _
Cell(x, rowHead) & ": " & _
"</strong>" & _
Cell(x, rowData)
Case 6, 9, 14, 15
msgText = _
"<strong style='color: red;'>" & _
Cell(x, rowHead) & ": " & _
"</strong>" & _
Cell(x, rowData)
Case Else
'Not really necessary, as you really want to skip any columns
'that you don't want, but your could put whatever doesn't quite
'fit here.
End Select
htmlMsg = htmlMsg & msgText
Next x
Обратите внимание на то, как я использовал оператор Select Case - если определенные столбцы в вашем списке не требуются в вашем электронном письме, не включайте их в строки оператора Case, так они будут пропущены.
На самом деле, я не могу сделать это яснее этого.
Тем не менее, неплохо было бы прочитать инструкцию PHP switch, которую я включил в комментарии к вашему сообщению.
Заголовки на листе Excel не могут быть перемещены, однако это не должно быть проблемой, поскольку используемые ячейки являются всего лишь выделением, а не полным диапазоном, как вы можете видеть в коде моего вопроса. Так что я могу включить заголовки в выборку и попробовать. Я отправлю ответ позже, если метод сработает. - Мне не нравится идея добавлять это в виде строк. Это не кажется чистым. Дополнительный рабочий лист с сохраненными заголовками, я думаю, был бы «простым, но неряшливым» способом делать что-то, учитывая, что список может быть создан внутри самого кода, а это делает его громоздким. Внутренний список я тоже мог бы попробовать. Спасибо!
Ха-ха! Я полагаю, что в подлости нет ничего плохого. Если работает, значит работает! Я просто предпочитаю управлять машиной руками, чем ногами. Делает работу проще и эффективнее: P
Привет @Paul, я пробовал ваши методы, но я не вижу никакого способа использовать индивидуальное форматирование html для определенных строк. Я минимизировал раздел html_text и добавил еще немного html, который требуется, но вместо того, чтобы каждый раз отправлять ВСЕ строки, мне нужно, чтобы номер ячейки увеличивался каждый раз на 1 (i = i + 1) и добавлял к правильной строке + html (строка + html также потребует aj = J + 1, я полагаю? Тем не менее, все еще не знаете, как это реализовать.
Все, что вам нужно сделать в вашем случае, - это проверить значение x (Select Case x), сравнить его с конкретным значением и при необходимости добавить стиль к шрифту. На самом деле это не ракетостроение, но я оставлю это вам. Возможно, вам захочется взять руль своими руками, а не шофером, который будет использовать его ноги!
В ответ на обновление, которое вы добавили от 19.07.2018. Я решил проблему форматов html. Я пробовал такие теги, как <strong>, <h3>, </br>, style='color: green;', которые, как я обнаружил, не работают. Он принимает только <b> для жирного шрифта, <font size = "18"> для калибровки и <font color='green'> для раскраски, и, как ни странно, он принимает <br> but not </br>. Кроме того, есть заголовки на других листах, но лист, который меня попросили отправить по электронной почте, представляет собой сводку всех итогов со всех листов в виде набора ячеек. Следовательно, для сводной таблицы нет заголовков.
Да - это <br />, а не </br>. Вы предпочитаете жирный и курсивный шрифт.
... и вы можете добавить итоговый сводный лист, используя формат, который вы хотите отображать в электронном письме, и сэкономить вам много работы.
Я добавил второе изображение некоторых фиктивных данных, передаваемых из сводных ежемесячных цифр, и стиль не является моим предпочтением, его предпочитают директора. Ранее я спрашивал в StackOverflow, есть ли способ передать диапазон от Excel до электронной почты нажатием кнопки, сохраняя форматирование, и не получил ответа. : /
Мой диапазон и ввод теперь полностью работают. Проблема только с вводом HTML в кейсы. См. Обновление вопроса и снимок экрана.
В электронное письмо не передается никакого форматирования, будь то сводная таблица или нет. Вот почему я пытаюсь добавить HTML с помощью Select Case.
Не проверено: удаление всех ваших следующих i и добавление только одного после последнего html_text = ...? (это только один цикл For Next)