VBA Multiline String Issues - string

I am not having much experience writing VBA script, I am almost lost to find out in the multiline string. Where exactly I am lost is when I try to split the String in multiple lines, could you help me how to end
Working String is below before split:
strSQL = "insert into ded_limit_analysis (PDPD_ID,PDDS_DESC,PRODUCT_CAT,BASE_PDPD_ID,PROD_CYCLE,HMO_IND_DED) " & vbCrLf & _
"values (" & "'" & Me.txt_pdpd_id & "'" & "," & "'" & Me.txt_pdds & "'" & "," & "'" & Me.cbx_prod_type & "'" & "," & "'" & Me.txt_base_pdpd & "'" & "," & "'" & Me.cbx_prod_cycle & "'" & "," & "'" & Me.txt_hmo_ind_ded & "'" & ")"
The one not working is below, I am trying to split the lines because I have many columns to include in insert and it is more than 1000 caracters and not able to fit in single line (below is just sample, actual is much longer and I am forced to split the lines).
strSQL = "insert into ded_limit_analysis (PDPD_ID,PDDS_DESC,PRODUCT_CAT,BASE_PDPD_ID,PROD_CYCLE,HMO_IND_DED) " & vbCrLf & _
"values (" & "'" & Me.txt_pdpd_id & "'" & "," & "'" & Me.txt_pdds & "'" & "," & "'" & Me.cbx_prod_type & "'" & "," & "'" & Me.txt_base_pdpd & "'" & "," & "'" & Me.cbx_prod_cycle & "'" & "," & " & vbCrLf &" _
& "'" & Me.txt_hmo_ind_ded & "'" & ")"
Please advice where I am messing up, thanks

You need to start the next line with "&"
So:
strSQL = "insert into ded_limit_analysis (PDPD_ID,PDDS_DESC,PRODUCT_CAT,BASE_PDPD_ID,PROD_CYCLE,HMO_IND_DED) " _
& vbCrLf & "values (" & "'" & Me.txt_pdpd_id & "'" & "," _
& "'" & Me.txt_pdds & "'" & "," & "'" & Me.cbx_prod_type _
& "'" & "," & "'" & Me.txt_base_pdpd & "'" & "," & "'" _
& Me.cbx_prod_cycle & "'" & "," & vbCrLf _
& "'" & Me.txt_hmo_ind_ded & "'" & ")"
Although, looking at the string, you can eliminate a lot of the "&" in your code. This would be cleaner:
strSQL = "insert into ded_limit_analysis (PDPD_ID, " _
& "PDDS_DESC, " _
& "PRODUCT_CAT, " _
& "BASE_PDPD_ID, " _
& "PROD_CYCLE, " _
& "HMO_IND_DED) " _
& " values ('" & Me.txt_pdpd_id & "', '" _
& Me.txt_pdds & "', '" _
& Me.cbx_prod_type & "', '" _
& Me.txt_base_pdpd & "', '" _
& Me.cbx_prod_cycle & "', '" _
& Me.txt_hmo_ind_ded & "')"
It's just much easier to understand this way. Also, you don't need "vbCrLf" in your SQL. It's just white space.

On the second string vbCrLf is within quotes and is seen as a string rather than a command.
Try this code in place of the problem line above:
strSQL = "insert into ded_limit_analysis (PDPD_ID,PDDS_DESC,PRODUCT_CAT,BASE_PDPD_ID,PROD_CYCLE,HMO_IND_DED) " & vbCrLf & _
"values (" & "'" & Me.txt_pdpd_id & "'" & "," & "'" & Me.txt_pdds & "'" & "," & "'" & Me.cbx_prod_type & "'" & "," & "'" & Me.txt_base_pdpd & "'" & "," & "'" & Me.cbx_prod_cycle & "'" & "," & vbCrLf _
& "'" & Me.txt_hmo_ind_ded & "'" & ")"

I tried with this option after seraching other post and works, thanks for proving other solutions, appreciate that.
strSQL = "insert into ded_limit_analysis (PDPD_ID,PDDS_DESC,PRODUCT_CAT,BASE_PDPD_ID,PROD_CYCLE,HMO_IND_DED) " & vbCrLf & _
"values (" & "'" & Me.txt_pdpd_id & "'" & "," & "'" & Me.txt_pdds & "'" & "," & "'" & Me.cbx_prod_type & "'" & "," & "'" & Me.txt_base_pdpd & "'" & "," & "'" & Me.cbx_prod_cycle & "'" & ","
strSQL = strSQL & "'" & Me.txt_hmo_ind_ded & "'" & ")"

Related

Paste Workbook.Queries into arrays without pasting to sheet

So I have a bit of a problem with some query connections that I want to deal with inside an array because they can hold more rows than Excel can handle.
Option Explicit
Sub RefrescaConsultas()
EliminaConsultas
CreaConsultas
End Sub
Private Sub EliminaConsultas()
Dim Consulta As Object
For Each Consulta In ThisWorkbook.Queries
Consulta.Delete
Next Consulta
End Sub
Private Sub CreaConsultas()
Dim Mes As String: Mes = HMacro.Range("B2")
Dim Año As Long: Año = HMacro.Range("B1")
Dim MesNum As Byte: MesNum = Month(DateValue("01/" & Mes & "/2020"))
Dim RutaAccess As String: RutaAccess = Chr(34) & "\\ate2899cor01\reporting_administrativos\TELEFONICA\GP\Informe Evolucion Territorios\2020\Modelo Marzo´20\Inforrme Evolucion Ventas\Nuevo informe\BBDD\Actualiza Conversores.accdb" & Chr(34)
'Brutas
ThisWorkbook.Queries.Add "Brutas", "let" & Chr(13) & "" & Chr(10) & " Origen = Access.Database(File.Contents(" & RutaAccess & "), [CreateNavigationProperties=true])," & Chr(13) & "" & Chr(10) & " _Brutas = Origen{[Schema="""",Item=""Brutas""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Columnas quitadas"" = Table.Rem" & _
"oveColumns(_Brutas,{""fx_proceso"", ""fx_estado_fin"", ""fx_devengo"", ""estado"", ""cod_indicador_negocio_alta_comercial"", ""producto_alta_comercial"", ""subproducto_origen_alta_comercial"", ""soporte"", ""faro"", ""codigo_pedido"", ""tipo_doc"", ""id_fiscal"", ""CUC"", " & _
"""telefono"", ""segmento"", ""provincia_cliente"", ""ccaa_cliente"", ""territorio_cliente"", ""vendedor"", ""canal_venta"", ""co_proveedor"", ""no_empresa"", ""co_centro_venta"", ""provincia_venta"", ""ccaa_venta"", ""territorio_venta"", ""FechaGrab"", ""unidades"", ""producto_comision_alta_comercial"", ""producto_comision_actualizad" & _
"o"", ""importe_comision"", ""COD_T9"", ""rf_tq"", ""operacion"", ""sub_producto_destino_alta_comercial"", ""num_lineas_movil_tipo_fusion"", ""num_lineas_movil_planta"", ""in_fusion"", ""anul_15"", ""anul_30"", ""anul_60"", ""co_resolucion_sia"", ""resolucion_sia"", ""causa_anulacion"", ""fuente_origen"", ""cliente_nuevo"", ""in_servicio_tv""})," & Chr(13) & "" & Chr(10) & " #""Filas filtradas"" = Table.SelectRows(#""Columnas quitadas"", each Dat" & _
"e.Month([fx_solicitud]) = " & MesNum & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filas filtradas"""
'TV
ThisWorkbook.Queries.Add "TV", "let" & Chr(13) & "" & Chr(10) & " Origen = Access.Database(File.Contents(" & RutaAccess & "), [CreateNavigationProperties=true])," & Chr(13) & "" & Chr(10) & " _TV = Origen{[Schema="""",Item=""TV""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Columnas quitadas"" = Table.RemoveColum" & _
"ns(_TV,{""fx_proceso"", ""fx_estado_fin"", ""fx_devengo"", ""estado"", ""operacion"", ""cod_indicador_negocio_alta_comercial"", ""producto_alta_comercial"", ""sub_producto_destino_alta_comercial"", ""subproducto_origen_alta_comercial"", ""soporte"", ""codigo_pedido"", ""tipo_doc"", ""id_fiscal"", ""CUC"", ""telefono"", ""segmento"", ""provincia_cliente"", ""ccaa_cli" & _
"ente"", ""territorio_cliente"", ""vendedor"", ""canal_venta"", ""co_proveedor"", ""no_empresa"", ""co_centro_venta"", ""no_sucursal"", ""provincia_venta"", ""ccaa_venta"", ""territorio_venta"", ""FechaGrab"", ""unidades"", ""baja_prematura"", ""dias_baja"", ""producto_comision_alta_comercial"", ""importe_comision"", ""COD_T9"", ""rf_tq"", ""nu_administra"", ""fuente" & _
"_origen"", ""ds_fusion_origen"", ""ds_fusion_destino"", ""baja_prematura_8_mes_sig"", ""IN_PLANTA_8_MES_SIG"", ""CLIENTE_NUEVO""})," & Chr(13) & "" & Chr(10) & " #""Filas filtradas"" = Table.SelectRows(#""Columnas quitadas"", each Date.Month([fx_solicitud]) = " & MesNum & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filas filtradas"""
'Fusion
ThisWorkbook.Queries.Add "Fusion", "let" & Chr(13) & "" & Chr(10) & " Origen = Access.Database(File.Contents(" & RutaAccess & "), [CreateNavigationProperties=true])," & Chr(13) & "" & Chr(10) & " _Fusion = Origen{[Schema="""",Item=""Fusion""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Columnas quitadas"" = Table.Rem" & _
"oveColumns(_Fusion,{""fx_proceso"", ""fx_solicitud"", ""fx_devengo"", ""fx_instalacion"", ""estado"", ""operacion"", ""cod_indicador_negocio_alta_comercial"", ""producto_alta_comercial"", ""sub_producto_destino_alta_comercial"", ""subproducto_origen_alta_comercial"", ""soporte"", ""codigo_pedido"", ""tipo_doc"", ""id_fiscal"", ""telefono"", ""segmento"", ""provincia" & _
"_cliente"", ""ccaa_cliente"", ""territorio_cliente"", ""vendedor"", ""matricula_origen"", ""canal_venta"", ""co_proveedor"", ""no_empresa"", ""co_centro_venta"", ""provincia_venta"", ""ccaa_venta"", ""territorio_venta"", ""FechaGrab"", ""unidades"", ""baja_prematura"", ""producto_comision_alta_comercial"", ""COD_T9"", ""valor_origen"", ""valor_destino"", ""rf_tq"", " & _
"""dif_dias_baja"", ""in_servicio_tv_origen"", ""in_servicio_tv_destino"", ""num_lineas_movil_tipo_fusion"", ""num_lineas_movil_planta"", ""CUC"", ""fuente_origen"", ""fx_alta_desco""})," & Chr(13) & "" & Chr(10) & " #""Filas filtradas"" = Table.SelectRows(#""Columnas quitadas"", each Date.Month([fx_estado_fin]) = " & MesNum & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filas filtradas"""
'Inserciones
ThisWorkbook.Queries.Add "Inserciones", "let" & Chr(13) & "" & Chr(10) & " Origen = Access.Database(File.Contents(" & RutaAccess & "), [CreateNavigationProperties=true])," & Chr(13) & "" & Chr(10) & " _Inserciones = Origen{[Schema="""",Item=""Inserciones""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Columnas quitadas"" =" & _
" Table.RemoveColumns(_Inserciones,{""fx_proceso"", ""fx_estado_fin"", ""estado"", ""causa_estado"", ""operacion"", ""cod_indicador_negocio_alta_comercial"", ""indicador_negocio_alta_comercial"", ""subproducto_origen_alta_comercial"", ""soporte"", ""codigo_pedido"", ""tipo_doc"", ""id_fiscal"", ""CUC"", ""telefono"", ""segmento"", ""provi" & _
"ncia_cliente"", ""ccaa_cliente"", ""territorio_cliente"", ""vendedor"", ""canal_venta"", ""co_proveedor"", ""no_empresa"", ""co_centro_venta"", ""provincia_venta"", ""ccaa_venta"", ""territorio_venta"", ""FechaGrab"", ""unidades"", ""cod_comision_alta_comercial"", ""producto_comision_alta_comercial"", ""importe_comision"", ""co_contrato"", ""co_plantari"", ""operado" & _
"r_origen"", ""operador_destino"", ""ICC"", ""LIQUIDABLE"", ""TARJETA_VIRTUAL"", ""NUMERO_REPETICIONES"", ""FUENTE_ORIGEN""})," & Chr(13) & "" & Chr(10) & " #""Filas filtradas"" = Table.SelectRows(#""Columnas quitadas"", each Date.Month([fx_solicitud]) = " & MesNum & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filas filtradas"""
'Prosegur
ThisWorkbook.Queries.Add "Prosegur", "let" & Chr(13) & "" & Chr(10) & " Origen = Access.Database(File.Contents(" & RutaAccess & "), [CreateNavigationProperties=true])," & Chr(13) & "" & Chr(10) & " _Prosegur = Origen{[Schema="""",Item=""Prosegur""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Columnas quitadas"" = Table" & _
".RemoveColumns(_Prosegur,{""fx_proceso"", ""fx_estado_fin"", ""fx_devengo"", ""estado"", ""operacion"", ""cod_indicador_negocio_solicitado"", ""indicador_negocio_solicitado"", ""producto_solicitado"", ""sub_producto_destino_solicitado"", ""subproducto_origen_solicitado"", ""cod_indicador_negocio_alta_comercial"", ""producto_alta_comercial"", ""sub_producto_destino_a" & _
"lta_comercial"", ""subproducto_origen_alta_comercial"", ""soporte"", ""codigo_pedido"", ""CUC"", ""tipo_doc"", ""id_fiscal"", ""telefono"", ""segmento"", ""localidad_cliente"", ""provincia_cliente"", ""ccaa_cliente"", ""territorio_cliente"", ""vendedor"", ""matricula_origen"", ""canal_venta"", ""co_proveedor"", ""no_empresa"", ""co_centro_venta"", ""provincia_venta" & _
""", ""ccaa_venta"", ""territorio_venta"", ""pais_vendedor"", ""FechaGrab"", ""FechaGrabInci"", ""in_fusion"", ""tipo"", ""nu_administra"", ""unidades"", ""id_senializacion"", ""cod_comision_solicitado"", ""producto_comision_solicitado"", ""producto_comision_alta_comercial"", ""id_lead"", ""COD_T9"", ""rf_tq"", ""producto_comision_actualizado"", ""fuente_origen"", """ & _
"co_unico"", ""fecha_compromiso_ini"", ""fecha_alta_sistema"", ""Campo61"", ""Campo62"", ""Campo63""})," & Chr(13) & "" & Chr(10) & " #""Filas filtradas"" = Table.SelectRows(#""Columnas quitadas"", each Date.Month([fx_solicitud]) = " & MesNum & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filas filtradas"""
'Repos Móvil
ThisWorkbook.Queries.Add "Repos", "let" & Chr(13) & "" & Chr(10) & " Origen = Access.Database(File.Contents(" & RutaAccess & "), [CreateNavigationProperties=true])," & Chr(13) & "" & Chr(10) & " _Repos = Origen{[Schema="""",Item=""Repos""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Columnas quitadas"" = Table.Remov" & _
"eColumns(_Repos,{""fx_proceso"", ""fx_solicitud"", ""fx_devengo"", ""estado"", ""operacion"", ""cod_indicador_negocio_solicitado"", ""indicador_negocio_solicitado"", ""sub_producto_origen_alta_comercial"", ""subproducto_origen_alta_comercial"", ""cod_indicador_negocio_alta_comercial"", ""sub_producto_destino_alta_comercial"", ""subproducto_destino_alta_comercial"", " & _
"""soporte"", ""codigo_pedido"", ""tipo_doc"", ""id_fiscal"", ""CUC"", ""telefono"", ""segmento"", ""localidad_cliente"", ""provincia_cliente"", ""ccaa_cliente"", ""territorio_cliente"", ""vendedor"", ""matricula_origen"", ""canal_venta"", ""co_proveedor"", ""no_empresa"", ""co_centro_venta"", ""provincia_venta"", ""ccaa_venta"", ""territorio_venta"", ""pais_vendedor" & _
""", ""in_fusion"", ""tipo"", ""operador_origen"", ""operador_destino"", ""in_terminal"", ""FechaGrab"", ""FechaGrabInci"", ""co_contrato_origen"", ""co_contrato_destino"", ""co_plantari_origen"", ""co_plantari_destino"", ""cod_comision_solicitado"", ""producto_comision_solicitado"", ""producto_comision_alta_comercial"", ""ICC"", ""FUENTE_ORIGEN"", ""Arpu_Origen"", " & _
"""Arpu_Destino"", ""unidades""})," & Chr(13) & "" & Chr(10) & " #""Filas filtradas"" = Table.SelectRows(#""Columnas quitadas"", each Date.Month([fx_estado_fin]) = " & MesNum & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filas filtradas"""
'Terminales
ThisWorkbook.Queries.Add "Terminales", "let" & Chr(13) & "" & Chr(10) & " Origen = Access.Database(File.Contents(" & RutaAccess & "), [CreateNavigationProperties=true])," & Chr(13) & "" & Chr(10) & " _Terminales = Origen{[Schema="""",Item=""Terminales""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Columnas quitadas"" = T" & _
"able.RemoveColumns(_Terminales,{""fx_proceso"", ""fx_solicitud"", ""fx_devengo"", ""estado"", ""operacion"", ""cod_indicador_negocio_alta_comercial"", ""producto_alta_comercial"", ""sub_producto_destino_alta_comercial"", ""subproducto_origen_alta_comercial"", ""soporte"", ""codigo_pedido"", ""tipo_doc"", ""id_fiscal"", ""CUC"", ""telefono"", ""segmento"", ""provinci" & _
"a_cliente"", ""ccaa_cliente"", ""territorio_cliente"", ""vendedor"", ""canal_venta"", ""co_proveedor"", ""no_empresa"", ""co_centro_venta"", ""provincia_venta"", ""ccaa_venta"", ""territorio_venta"", ""FechaGrab"", ""unidades"", ""producto_comision_alta_comercial"", ""importe_comision"", ""vendedor_entrega"", ""canal_venta_entrega"", ""agrupacion_canal_entrega"", """ & _
"canal_entrega"", ""detalle_canal_entrega"", ""co_proveedor_entrega"", ""no_empresa_entrega"", ""co_centro_venta_entrega"", ""no_sucursal_entrega"", ""provincia_venta_entrega"", ""territorio_venta_entrega"", ""tipo"", ""gama_terminal"", ""in_financiado"", ""nu_imei"", ""cod_campania"", ""FUENTE_ORIGEN"", ""Campo56"", ""Campo57"", ""Campo58"", ""Campo59"", ""Campo60""" & _
", ""Campo61""})," & Chr(13) & "" & Chr(10) & " #""Filas filtradas"" = Table.SelectRows(#""Columnas quitadas"", each Date.Month([fx_estado_fin]) = " & MesNum & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filas filtradas"""
'Móvil
ThisWorkbook.Queries.Add "Movil", "let" & Chr(13) & "" & Chr(10) & " Origen = Access.Database(File.Contents(" & RutaAccess & "), [CreateNavigationProperties=true])," & Chr(13) & "" & Chr(10) & " _Movil = Origen{[Schema="""",Item=""Movil""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Columnas quitadas"" = Table.Remov" & _
"eColumns(_Movil,{""fx_proceso"", ""fx_solicitud"", ""fx_devengo"", ""estado"", ""operacion"", ""cod_indicador_negocio_alta_comercial"", ""subproducto_origen_alta_comercial"", ""co_modven"", ""soporte"", ""codigo_pedido"", ""tipo_doc"", ""id_fiscal"", ""CUC"", ""telefono"", ""segmento"", ""provincia_cliente"", ""ccaa_cliente"", ""territorio_cliente"", ""vendedor"", " & _
"""canal_venta"", ""co_proveedor"", ""no_empresa"", ""co_centro_venta"", ""provincia_venta"", ""ccaa_venta"", ""territorio_venta"", ""FechaGrab"", ""unidades"", ""baja_prematura"", ""dif_dias_baja"", ""producto_comision_alta_comercial"", ""importe_comision"", ""in_terminal"", ""co_contrato"", ""co_plantari"", ""operador_origen"", ""operador_destino"", ""ICC"", ""fuen" & _
"te_origen""})," & Chr(13) & "" & Chr(10) & " #""Filas filtradas"" = Table.SelectRows(#""Columnas quitadas"", each Date.Month([fx_estado_fin]) = " & MesNum & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filas filtradas"""
'TMO
ThisWorkbook.Queries.Add "TMO", "let" & Chr(13) & "" & Chr(10) & " Origen = Access.Database(File.Contents(" & RutaAccess & "), [CreateNavigationProperties=true])," & Chr(13) & "" & Chr(10) & " _TMO = Origen{[Schema="""",Item=""TMO""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Columnas quitadas"" = Table.RemoveCol" & _
"umns(_TMO,{""semana"", ""New_Territorio"", ""PAIS_TABLA"", ""MODO TABLA"", ""MODO TABLA TMO"", ""FX_LLAMADA"", ""NO_SEGMENTO"", ""NO_TERRITORIO"", ""NO_SUBTERRITORIO"", ""NO_PROVEEDOR"", ""NO_ORIGEN"", ""Terri_cliente"", ""Subterri_cliente"", ""ORIGEN"", ""NO_SEGMENTO_SKILL"", ""CO_GRABACION"", ""CLIENTE_NUEVO"", ""DS_SEGMENTO_ORGANIZATIVO"", ""B2C"", ""Idioma"", """ & _
"CO_TIPO_EMISION"", ""IN_AGENDADA"", ""CA_RECIBIDAS"", ""CA_LLAMADAA_VALIDAA"", ""CA_Atendidas_Entrantes"", ""CA_Aten_20seg"", ""CA_Conv_M20Seg"", ""CA_TMO"", ""CA_TMO_S"", ""CA_TME"", ""CA_Tr_Imputables"", ""CA_Transferidas"", ""CA_Salientes"", ""CA_AGENDADAS"", ""CA_TMO_AGENDADAS""})," & Chr(13) & "" & Chr(10) & " #""Filas filtradas"" = Table.SelectRows(#""Columnas quitadas"", each [Mes] =" & _
MesNum & ")," & Chr(13) & "" & Chr(10) & " #""Filas filtradas1"" = Table.SelectRows(#""Filas filtradas"", each [Año] = " & Año & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filas filtradas1"""
End Sub
The code is fairly simple, I've manually recorded Data->from data base->selected the data base->deleted some columns for each connection and filtered some data.
Now the workbook has all these connections that I need to work with, but pasting them into a sheet and then into an array might be a problem because some of them are more than 1M rows... Any Insight on how to achieve this?
Specifications and Limits for Excel Worksheets and Workbooks
Total number of rows and columns in a worksheet :
1,048,576 rows and 16,384 columns
so you may have to add a clause to limit the number of rows: select TOP 1000 in your SQL request
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Customer;Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT TOP 10OO fx_proceso FROM [Prosegur]")

Unable to set the FormulaArray of the Range Class -- Less than 255, not using replace method

all:
I feel like this is something painfully obvious but I have been banging my head up against the wall for a while and can't seem to find a solution.
When entering the below formula into "M3"
=IFERROR(IF(ISBLANK(VLOOKUP(A3&"|"&E3,CHOOSE({1,2},OLD_PR!$A$3:$A$374&"|"&OLD_PR!$E$3:$E$374,OLD_PR!$O$3:$O$374),2,FALSE)),"",VLOOKUP(A3&"|"&E3,CHOOSE({1,2},OLD_PR!$A$3:$A$374&"|"&OLD_PR!$E$3:$E$374,OLD_PR!$O$3:$O$374),2,FALSE)),"")
with this code (ActiveCell = "M3")
ActiveCell.FormulaArray = _
"=IFERROR(IF(ISBLANK(VLOOKUP(A3&" & Chr(34) & "|" & Chr(34) & "&E3,CHOOSE({1,2},OLD_PR!$A$3:$A$" & OldPRLastRow & "&" & Chr(34) & "|" & Chr(34) & "&OLD_PR!$E$3:$E$" & OldPRLastRow & ",OLD_PR!$O$3:$O$" & OldPRLastRow & "),2,FALSE)),""""," _
& "VLOOKUP(A3&" & Chr(34) & "|" & Chr(34) & "&E3,CHOOSE({1,2},OLD_PR!$A$3:$A$" & OldPRLastRow & "&" & Chr(34) & "|" & Chr(34) & "&OLD_PR!$E$3:$E$" & OldPRLastRow & ",OLD_PR!$O$3:$O$" & OldPRLastRow & "),2,FALSE))," _
& Chr(34) & Chr(34) & ")"
I am getting the Run-time error in the title.
When I manually enter the formula, it works.
The formula is less than 255 characters without the replace work around, so I'm not making any mistakes there
I'm only entering the formula into a single cell
The above are the most common mistakes I found via google searches, but do not apply to me. I'm sure this is something silly.
Any insight would be greatly appreciated!
With reference to this try
ActiveCell.FormulaArray = _
"=IFERROR(IF(ISBLANK(VLOOKUP(D3&" & Chr(34) & "|" & Chr(34) & "&E3,""ChoosePart"",2,FALSE)),""""," _
& "VLOOKUP(D3&" & Chr(34) & "|" & Chr(34) & "&E3,""ChoosePart"",2,FALSE))," _
& Chr(34) & Chr(34) & ")"
ActiveCell.Replace """ChoosePart""", "CHOOSE({1,2},OLD_PR!$A$3:$A$" & OldPRLastRow & "&" & Chr(34) & "|" & Chr(34) & "&OLD_PR!$E$3:$E$" & OldPRLastRow & ",OLD_PR!$O$3:$O$" & OldPRLastRow & ")"
Since Column O contains text values, here's an alternative...
ActiveCell.FormulaArray = "=LOOKUP(REPT(""z"",255),CHOOSE({1,2},"""",INDEX(OLD_PR!$O$3:$O$" & OldPRLastRow & ",MATCH(A3&""|""&E3,OLD_PR!$A$3:$A$" & OldPRLastRow & "&""|""&OLD_PR!$E$3:$E$" & OldPRLastRow & ",0))))"

Send email to various addresses from cells

I have in "Sheet1" numerous email addresses, in columns K, M, O, Q, S, U, W, Y, AA.
I want to create an email that will be sent to all the addresses taken from the last row in Sheet1. Same for data in email body taken from last row.
Dim MonOutlook As Object
Dim MonMessage As Object
Dim EmailTo As String
With Worksheets("Sheet1")
EmailTo = .Range("K" & ligne) & ";" & .Range("M" & ligne) & ";" & .Range("O" & ligne) & ";" & .Range("Q" & ligne) & ";" & .Range("S" & ligne) & ";" & .Range("U" & ligne) & ";" & .Range("W" & ligne) & ";" & .Range("Y" & ligne) & ";" & .Range("AA" & ligne)
End With
Set MonOutlook = CreateObject("Outlook.Application")
Set MonMessage = MonOutlook.CreateItem(0)
MonMessage.To = ""
MonMessage.Cc = ""
MonMessage.Bcc = EmailTo
MonMessage.Subject = "Rate request" & " " & "for" & " " & ThisWorkbook.Sheets("Sheet1").Range("B" & ligne)
MonMessage.body = "Hello,"
Chr (13) & Chr(13) & "Please send me rate for" & " " & ThisWorkbook.Sheets("Sheet1").Range("G" & ligne) & " " & "rooms on basis" & " " & ThisWorkbook.Sheets("Sheet1").Range("H" & ligne) & _
Chr(13) & Chr(13) & "in hotel:" & " " & ThisWorkbook.Sheets("Sheet1").Range("J" & ligne) & _
Chr(13) & Chr(13) & "for the period" & " " & ThisWorkbook.Sheets("suivi").Range("C" & ligne) & " " & ThisWorkbook.Sheets("Sheet1").Range("D" & ligne) & _
Chr(13) & Chr(13) & "Thank you!" & _
Chr(13) & Chr(13) & Application.UserName & " " & "-" & " " & "x Tours"
MonMessage.Display
With ThisWorkbook.Sheets("Sheet1").Range("AB" & ligne)
.Value = Date
.NumberFormat = "dd/mm/yyyy"
End With
ActiveWorkbook.Save
Try the code below, explanations inside the code's comments.
Option Explicit
Sub EmailContactsLastRow()
Dim MonOutlook As Object
Dim MonMessage As Object
Dim EmailSht As Worksheet
Dim EmailTo As String
Dim ligne As Long
' set the worksheet object
Set EmailSht = ThisWorkbook.Sheets("Sheet1")
With EmailSht
ligne = .Cells(.Rows.Count, "K").End(xlUp).Row ' get last row with data in column K
EmailTo = .Range("K" & ligne) & ";" & .Range("M" & ligne) & ";" & .Range("O" & ligne) & ";" & _
.Range("Q" & ligne) & ";" & .Range("S" & ligne) & ";" & .Range("U" & ligne) & ";" & _
.Range("W" & ligne) & ";" & .Range("Y" & ligne) & ";" & .Range("AA" & ligne)
End With
Set MonOutlook = CreateObject("Outlook.Application")
Set MonMessage = MonOutlook.CreateItem(0)
With MonMessage
.To = ""
.Cc = ""
.Bcc = EmailTo
.Subject = "Rate request" & " " & "for" & " " & EmailSht.Range("B" & ligne)
.body = "Hello,"
Chr (13) & Chr(13) & "Please send me rate for" & " " & EmailSht.Range("G" & ligne) & " " & "rooms on basis" & " " & EmailSht.Range("H" & ligne) & _
Chr(13) & Chr(13) & "in hotel:" & " " & EmailSht.Range("J" & ligne) & _
Chr(13) & Chr(13) & "for the period" & " " & EmailSht.Range("C" & ligne) & " " & EmailSht.Range("D" & ligne) & _
Chr(13) & Chr(13) & "Thank you!" & _
Chr(13) & Chr(13) & Application.UserName & " " & "-" & " " & "x Tours"
.Display ' <-- this displays the email. not sending it
.send ' <-- this sends the email out
End With
With EmailSht.Range("AB" & ligne)
.Value = Date
.NumberFormat = "dd/mm/yyyy"
End With
ThisWorkbook.Save
End Sub

DSAL query for Unread mail in the filter for Outlook using Inbox.Items.Restrict

I am writing a code for automatically downloading an attachment from unread mail containing several keywords in the subject for example "training" but when I tried using SQL query for unread mail, it's giving me an error.
Filter = "#SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & _
Chr(34) & " Like '%Training%' AND " & _
Chr(34) & "urn:schemas:httpmail:hasattachment" & _
Chr(34) & "=1"
Set Items = Inbox.Items.Restrict(Filter) 'No error while running this code
Filter = "#SQL=" & Chr(34) & "& Chr(34) & "urn:schemas:httpmail:subject" & _
Chr(34) & " Like '%Training%' AND" & _
Chr(34) & "urn:schemas:httpmail:hasattachment" & _
Chr(34) & "= 1" & Chr(34) & "AND" & _
Chr(34) & "urn:schemas:httpmail:read" & _
Chr(34) & "= 0"
Set Items = Inbox.Items.Restrict(Filter)
' Now here it is giving me runtime error '-2147352567(800200009)'
All the help will be appreciated. Thanks in Advance
You almost got it,
The Error is coming from here Chr(34) & "= 1" & Chr(34) & "AND" & _
It Should be Chr(34) & "=1 AND " & _
Example
Filter = "#SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & _
Chr(34) & " Like '%Training%' AND " & _
Chr(34) & "urn:schemas:httpmail:hasattachment" & _
Chr(34) & "=1 AND " & _
Chr(34) & "urn:schemas:httpmail:read" & _
Chr(34) & "=0"
Filtering Items Using a String Comparison that DASL filters support includes equivalence, prefix, phrase, and substring matching. Note that when you filter on the Subject property, prefixes such as "RE: " and "FW: " are ignored.

How to delete specific commas and doublequotations from textfile

I am exporting a sheet as a CSV from Excel, but I am getting this line in the beginning of the CSV file:
"UTF-8","","","","","","","","","","","","","","","","","","","","","","","","","",""
So how do I get rid of this? I have tried CurrRow.Replace, etc. I can get it to replace words and whatnot, but not this line or any commas or double quotations.
Some help would really be appreciated.
Set UTFStream = CreateObject("adodb.stream")
UTFStream.Type = adTypeText
UTFStream.Mode = adModeReadWrite
UTFStream.Charset = "UTF-8"
UTFStream.LineSeparator = adLF
UTFStream.Open
'set field separator
ListSep = ","
'set source range with data for csv file
If Selection.Cells.Count > 1 Then
Set SrcRange = Selection
Else
Set SrcRange = ActiveSheet.UsedRange
End If
For Each CurrRow In SrcRange.Rows
'enclose each value with quotation marks and escape quotation marks in values
CurrTextStr = ""
For Each CurrCell In CurrRow.Cells
CurrTextStr = CurrTextStr & """" & CurrCell.Value & """" & ListSep
Next
'remove ListSep after the last value in line
While Right(CurrTextStr, 1) = ListSep
CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1)
'CurrRow.Replace What:=Chr(44) & "UTF-8" & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44) & Chr(34) & Chr(44) & Chr(44), Replacement:="X"
Wend
'add line to UTFStream
UTFStream.WriteText CurrTextStr, adWriteLine
Next
So this solved my issue. However, it works fine without the version check. I cannot get it to work with it, tried to debug it, but it seems like the path is correct?
Sub RemoveCommasDoubleQ()
' Enable a reference to 'Microsft Scripting Runtime'
' under VBA menu option Tools > References
Dim week, UserName As String
Dim MyFile, MyFilePath As String
Dim version As Integer
' Current week, XX
week = Format(Date, "ww")
' Username, e.g. niclas.madsen
UserName = Environ$("UserName")
' Initials, first letter of last and surname to caps
' e.g. niclas.madsen would be NM
UserName = UCase(Left(UserName, 1) & Mid(UserName, InStr(UserName, ".") + 1, 1))
' fix filename for saving purpose
MyFile = Replace(Replace("SupplierOrganization_W", "", ""), ".", "_") _
& "" _
& week _
& " " _
& UserName _
& ".csv"
'SupplierOrganization_WXX NM
MyFilePath = getDirSubParentPath & MyFile
' Version check
Do While Len(Dir(MyFilePath)) <> 0
version = version + 1
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
Loop
'Const tmpFile As String = "C:\Users\niclas.madsen\Desktop\AP\tmp_file.txt"
Dim tmpFile, tmpFilePath As String
tmpFile = getDirSubParentPath & "tmp_file.txt"
Dim tmpString As String
'Dim fso As New FileSystemObject
Dim fso As Object 'scripting.filesystemobject
Set fso = CreateObject("scripting.filesystemobject")
If fso.FileExists(MyFilePath) = True Then
Application.ScreenUpdating = False
Open MyFilePath For Input As #1
Open tmpFile For Output As #2
tmpString = Input(LOF(1), 1) 'read the entire file
tmpString = Replace(tmpString, (Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34)), "") 'eliminate double quotation and commas in the first line with UTF-8
Print #2, tmpString 'output result
Close #1
Close #2
fso.DeleteFile (MyFilePath) 'delete original file
fso.CopyFile tmpFile, MyFilePath, True 'rename temp file
fso.DeleteFile (tmpFile) 'delete temp file
Application.ScreenUpdating = True
MsgBox "Finished processing file", vbInformation, "Done!"
Else
MsgBox "Cannot locate the file : " & MyFile, vbCritical, "Error"
End If
Set fso = Nothing
End Sub
' Get Parent Sub Directory Path
Function getDirSubParentPath()
getDirSubParentPath = ThisWorkbook.Path & Application.PathSeparator & "CSV" & Application.PathSeparator & "Parent" & Application.PathSeparator
End Function

Resources