Ir ao conteúdo
  • Cadastre-se

Midori

Membro Pleno
  • Posts

    3.543
  • Cadastrado em

  • Última visita

Tudo que Midori postou

  1. @Kadu Du Com TEXTSPLIT separo os elementos do texto usando o espaço como delimitador. O retorno vem na forma matricial e cada coluna é um elemento: Na primeira e segunda linha foram 4 e na última 5. Veja que o penúltimo elemento é onde tem o conjuto de dados com as operações. Então é só contar e retornar a posição - 1. Separando novamente com o delimitador "X" vem na forma numérica. Depois é só aplicar PRODUCT/MULT para multiplicar. Obs: Se tiver mais espaços (ou nenhum) entre o penúltimo e último conjunto vai dar erro na fórmula.
  2. @Kadu Du Para o excel português TEXTSPLIT deve ser DIVIDIRTEXTO ou TEXTODIVISAO.
  3. Se o padrão é acumular pontos de 10 em 10 para subir de nível, não há necessidade de tabela para pesquisar. O nível atual é a parte inteira da divisão da Exp Atual por 10 + 1. E o que faltará para o próximo nível será o produto do Nível Atual por 10 menos Exp Atual.
  4. @Guilherme Stoduto Acho mais simples fazer como comentei, veja que não atribuí um por um manualmente. No seu código para preencher as outras linhas é só colocar um contador, p.ex, Dim LinhaRM As Long ... Sheets("RM").Range("B2").Offset(LinhaRM).Value = CodMaterial Sheets("RM").Range("C2").Offset(LinhaRM).Value = Descricao ... LinhaRM = LinhaRM + 1
  5. @Kadu Du No Excel 365 você pode usar a fórmula separar TEXTSPLIT para tentar pegar esses valores assim, =1,07*MULT(VALOR(TEXTSPLIT(ÍNDICE(TEXTSPLIT(A1;" ");CONT.VALORES(TEXTSPLIT(A1;" "))-1);"X")))
  6. @Guilherme Stoduto Como os campos não estão organizados em sequencia e são vários, para facilitar pode ser aplicada a função de busca pelo nome dos camspos. Assim não terá que tratar cada um e atribuir manualmente, p.ex, Const CODIGO_MATERIAL As String = "CÓDIGO MATERIAL" Const DESCRICAO_MATERIAL As String = "DESCRIÇÃO MATERIAL" Const QUANTIDADE_SOLICITADA As String = "QUANTIDADE SOLICITADA" Const CHAPA As String = "CHAPA" Const SUPERVISOR As String = "SUPERVISOR" Const COD_PESSOA As String = "COD PESSOA" Const SEGMENTO As String = "SEGMENTO" Const LOCALIDADE_DESTINO As String = "LOCALIDADE DESTINO" Const RETIRADA As String = "RETIRADA" Const DATARG As String = "DATA" Const LINHA_CAMPO_REQ As Integer = 5 Sub SalvaRequisicoes() Dim Area As Range Dim Campo As Range Dim Requisicao As Object Dim Linha As Long Set Area = ThisWorkbook.Sheets("REQUISIÇÃO").[A1:E5] For Linha = 1 To 3 Set Requisicao = BuscaRequisicao(Area, Linha) If Requisicao Is Nothing Then MsgBox "Erro, campo inválido", vbExclamation Exit For End If For Each Campo In Workbooks("RELATÓRIO.xlsx").Sheets("RELATÓRIO").[A2:K2] If Requisicao.Exists(Campo.Value) Then Campo(Linha + 1).Value = Requisicao.Item(Campo.Value) End If Next Campo Next Linha Set Requisicao = Nothing End Sub Function BuscaRequisicao(Area As Range, ByVal Linha As Double) As Object Dim Campo As Variant Dim Valor As Variant Dim Indice As Integer Dim Requisicao As Object Dim Busca As Range Set Requisicao = CreateObject("Scripting.Dictionary") Campo = Array( _ CODIGO_MATERIAL, _ DESCRICAO_MATERIAL, _ QUANTIDADE_SOLICITADA, _ CHAPA, _ SUPERVISOR, _ COD_PESSOA, _ SEGMENTO, _ LOCALIDADE_DESTINO, _ RETIRADA, _ DATARG) For Each Valor In Campo Set Busca = Area.Find(What:=Valor, LookIn:=xlValues, LookAt:=xlWhole) If Not Busca Is Nothing Then If Busca.Row = LINHA_CAMPO_REQ Then Call Requisicao.Add(Campo(Indice), Busca(Linha + 1).Value) Else Call Requisicao.Add(Campo(Indice), Busca(2).Value) End If Indice = Indice + 1 Else Exit For End If Next Valor If UBound(Campo) + 1 <> Indice Then Set Requisicao = Nothing End If Set BuscaRequisicao = Requisicao End Function O código assume que são 10 campos e os nomes deles nas duas planilhas devem ser os mesmos. A macro deve ficar no módulo da planilha Requisição e nesse teste só pega 3 registros. Você pode editar o loop das linhas para pegar a quantidade automaticamente. Para mandar um registro para o relatório é só passar o número da linha da tabela para o segundo argumento. O registro p.ex da linha 20 para a primeira linha da outra, Set Requisicao = BuscaRequisicao(Area, 20) For Each Campo In Workbooks("RELATÓRIO.xlsx").Sheets("RELATÓRIO").[A2:K2] If Requisicao.Exists(Campo.Value) Then Campo(2).Value = Requisicao.Item(Campo.Value) End If Next Campo
  7. O evento que ativa a macro é o Calculate que acontece quando as fórmulas da planilha são atualizadas, verifique o horário que começa a atualização da célula I13. O range da busca é N15:N27, caso tenha mudado tem que editar a macro.
  8. @Jessé Viana Vasconcelos Para puxar os novos dados automaticamente quando atualizar a tabela dinâmica, deixe no formato de tabela. Selecione e escolha Iniserir > Tabela. Depois insira a tabela dinâmica.
  9. Rodei sim e vi que esta funcionando. So mostrei os valores em hexadecimal poque estava comparando visualmente com a saida de hexdump. Era isso, com a diretiva a estrutura ficou com os dados corretos.
  10. @Jessé Viana Vasconcelos Isso pode ser feito com tabela dinâmica, adicione os campos, Depósito para colunas, Código e Texto nas linhas e Utilização em valores,
  11. @Thais marcondes Veja se este tópico ajuda, https://www.clubedohardware.com.br/forums/topic/1598381-código-vba-para-salvar-folhas-de-ponto-em-pdf-já-agrupadas-por-filial/ Se não conseguir resolver crie outro tópico com mais detalhes sobre a sua dificuldade.
  12. @arfneto Tentei carregar a estrutura dos headers numa única chamada de fread, porém os dados não vem da forma correta. Este é o hexdump de uma parte dele, 42 4D DA D3 05 00 00 00 00 00 36 00 00 00 28 00 O código só para pegar os valores dos primeiros campos, Signature 2 bytes e os outros de 4 bytes, #include <stdio.h> typedef struct { unsigned short signature; unsigned int size; unsigned int reserved; unsigned int offset; }BmpHeader; int main(int argc, char* argv[]) { FILE* infile = fopen("bitmap.bmp", "rb"); BmpHeader header; fread(&header, sizeof(BmpHeader), 1, infile); printf( "Signature: %x\n" "Size: %x\n" "Reserved: %x\n" "Offset: %x\n", header.signature, header.size, header.reserved, header.offset ); fclose(infile); return 0; } A saída fica assim, Signature: 4d42 Size: 5 Reserved: 360000 Offset: 280000 Mas devia ser assim, Signature: 4d42 Size: 5d3da Reserved: 0 Offset: 36 Para resolver isso tive que ler um por um ou tirar signature da estrutura para ler separadamente, p.ex, unsigned short signature; fread(&signature, sizeof(short), 1, infile); fread(&header, sizeof(BmpHeader), 1, infile);
  13. Esses valores estão na struct bmp_header de libbmp. Criei outra struct o para usar whpix->height (ou width) em vez de image.img_header.biHeight. Mas agora deixei o codigo mais simples, sem struct e a funcao limit que acho desnecessaria ja que os pixels sao unsinged char. O problema do desenquadramento que falei era algo com o formato da imagem. Resolvi isso na hora de converter outro formato para bmp no gimp ativando a opcao Do not write color space information. #include <stdio.h> #include <stdlib.h> #include "libbmp.h" int save_image( bmp_header* header, bmp_pixel** pixels, const char* filename ); int main(int argc, char* argv[]) { const char* infile = argv[1]; const char* outfile = argv[2]; FILE* file; bmp_img image; if(argc != 3){ fprintf(stderr, "Error: argc[%d]. Usage: imagebmp input.bmp output.bmp\n", argc); exit(1); } if((file = fopen(infile, "rb")) == NULL){ fprintf(stderr, "Can't open file: %s\n", infile); exit(1); } bmp_img_read(&image, infile); for(unsigned int y = 0; y < image.img_header.biHeight; y += 1){ for(unsigned int x = 0; x < image.img_header.biWidth; x += 1){ unsigned char* r = &image.img_pixels[y][x].red; unsigned char* g = &image.img_pixels[y][x].green; unsigned char* b = &image.img_pixels[y][x].blue; unsigned char luma = *r * 0.2999 + *g * 0.587 + *b * 0.114; /* unsigned char avg = (*r + *g + *b)/3; *r = avg; *g = avg; *b = avg; *r = 255 - *r; *g = 255 - *g; *b = 255 - *b; */ *r = luma; *g = luma; *b = luma; } } if(save_image(&image.img_header, image.img_pixels, outfile)){ fprintf(stderr, "Failed to save file: %s\n", outfile); exit(1); } return 0; } int save_image( bmp_header* header, bmp_pixel** pixels, const char* filename ){ bmp_img image; bmp_img_init_df(&image, header->biWidth, header->biHeight); for(unsigned int y = 0; y < header->biHeight; y += 1){ for(unsigned int x = 0; x < header->biWidth; x += 1){ bmp_pixel_init( &image.img_pixels[y][x], pixels[y][x].red, pixels[y][x].green, pixels[y][x].blue); } } if(bmp_img_write(&image, filename) != BMP_OK){ return 1; } bmp_img_free(&image); return 0; } Dois metodos para p&b (media e luma output3) e efeito negativo. Encontrei sobre isso nesta pagina, tem outas formulas, https://en.wikipedia.org/wiki/Grayscale
  14. Essa estutura não era realmente necessaria. Dessa vez so peguei os valores de img_pixels. Para facilitar fiz uma estrutura para armazenar os tamanhos usados nos loops. #include <stdio.h> #include <stdlib.h> #include "libbmp.h" typedef struct{ bmp_pixel** img_pixels; int width; int height; }WHPixels; WHPixels* load_image(const char* filename); int save_image(WHPixels* whpix, const char* filename); int limit(int x); int main(int argc, char* argv[]) { const char* input_filename = argv[1]; const char* output_filename = argv[2]; WHPixels* whpix; if(argc != 3){ fprintf(stderr, "Error: argc[%d]. Usage: imagebmp input.bmp output.bmp\n", argc); exit(1); } whpix = load_image(input_filename); if(whpix == NULL){ fprintf(stderr, "Can't read or open file: %s\n", input_filename); exit(1); } for(int y = 0; y < whpix->height; y += 1){ for(int x = 0; x < whpix->width; x += 1){ unsigned char red = whpix->img_pixels[y][x].red; whpix->img_pixels[y][x].red = whpix->img_pixels[y][x].green; whpix->img_pixels[y][x].green = red; } } if(save_image(whpix, output_filename)){ fprintf(stderr, "Failed to save file: %s\n", output_filename); exit(1); } return 0; } WHPixels* load_image(const char* filename){ FILE* file = fopen(filename, "rb"); WHPixels* whpix = NULL; bmp_img image; if(file == NULL){ return NULL; } whpix = (WHPixels*)malloc(sizeof(WHPixels)); bmp_img_read(&image, filename); whpix->width = image.img_header.biWidth; whpix->height = image.img_header.biHeight; whpix->img_pixels = image.img_pixels; fclose(file); return whpix; } int save_image(WHPixels* whpix, const char* filename){ bmp_img image; bmp_img_init_df(&image, whpix->width, whpix->height); for(int y = 0; y < whpix->height; y += 1){ for(int x = 0; x < whpix->width; x += 1){ bmp_pixel_init( &image.img_pixels[y][x], limit(whpix->img_pixels[y][x].red), limit(whpix->img_pixels[y][x].green), limit(whpix->img_pixels[y][x].blue) ); } } if(bmp_img_write(&image, filename) != BMP_OK){ return 1; } bmp_img_free(&image); return 0; } int limit(int x){ if(x > 255){ return 255; }else if (x < 0){ return 0; } return x; } Mas codigo tem um problema. Em vez de ficar preto e branco so troca as cores e deixa uma parte desenquadrada,
  15. @arfneto Cheguei a pensar nisso, mas como acabei não usando o retorno e só foquei em resolver a questão da conversão ficou void mesmo. Considero uma boa prática retornar algo. Por que é mais rápido?
  16. Achei esse projeto interessante e mudei um pouco a forma de preparar a imagem e converter. Tentei deixar mais simples e com alocação dinâmica para os arrays RGB e talvez tenha algum detalhe tecnicamente, ou do ponto de vista da boa prática de programação, incorreto nessa abordagem, mas para os testes rodou corretamente. Removi o imghelpers.c e o header e coloquei as funções "auxiliares" no mesmo source de main (chamei de imagebmp.c). No libbmp.c e o header não mudei nada. Para quem quiser testar tem que passar o nome da imagem como primeiro argumento e a saída para o segundo: imagebmp.exe input.bmp output.bmp #include <stdio.h> #include <stdlib.h> #include "libbmp.h" typedef struct { int width; int height; }Size; typedef struct { int** red; int** green; int** blue; }RGB; void alloc_rgb(RGB* RGB, int height, int width); void free_rgb(RGB* RGB, int width); Size* get_size(const char* filename); int limit(int x); void load_image(Size* img_size, RGB* RGB, const char* filename); void save_image(Size* img_size, RGB* RGB, const char* filename); int main(int argc, char* argv[]) { const char* input_filename = argv[1]; const char* output_filename = argv[2]; Size* img_size; RGB RGB; if (argc == 3) { FILE* file = fopen(input_filename, "r"); if (file == NULL) { fprintf(stderr, "Failed to open file: %s\n", input_filename); exit(1); } fclose(file); } else { fprintf(stderr, "Error: argc[%d]. Usage: imagebmp.exe input.bmp output.bmp", argc); exit(1); } img_size = get_size(input_filename); alloc_rgb(&RGB, img_size->height, img_size->width); if (img_size == NULL) { fprintf(stderr, "Can't read or open file: %s\n", input_filename); exit(1); } load_image(img_size, &RGB, input_filename); for (int y = 0; y < img_size->height; y += 1) { for (int x = 0; x < img_size->width; x += 1) { RGB.red[y][x] = RGB.green[y][x]; RGB.green[y][x] = RGB.red[y][x]; RGB.blue[y][x] = RGB.blue[y][x]; } } save_image(img_size, &RGB, output_filename); free_rgb(&RGB, img_size->height); return 0; } void alloc_rgb(RGB* RGB, int height, int width) { RGB->red = (int**)malloc(sizeof(int*) * height); RGB->green = (int**)malloc(sizeof(int*) * height); RGB->blue = (int**)malloc(sizeof(int*) * height); for (int i = 0; i < height; i += 1) { RGB->red[i] = (int*)malloc(sizeof(int) * width); RGB->green[i] = (int*)malloc(sizeof(int) * width); RGB->blue[i] = (int*)malloc(sizeof(int) * width); } } void free_rgb(RGB* RGB, int width) { for (int i = 0; i < width; i += 1) { free(RGB->red[i]); free(RGB->green[i]); free(RGB->blue[i]); } free(RGB->red); free(RGB->green); free(RGB->blue); } Size* get_size(const char* filename) { FILE* file = fopen(filename, "rb"); Size* img_size = NULL; bmp_img image; if (file != NULL) { img_size = (Size*)malloc(sizeof(Size)); bmp_img_read(&image, filename); img_size->height = image.img_header.biHeight; img_size->width = image.img_header.biWidth; bmp_img_free(&image); fclose(file); } return img_size; } int limit(int x) { if (x > 255) { return 255; } else if (x < 0) { return 0; } return x; } void load_image(Size* img_size, RGB* RGB, const char* filename) { bmp_img image; bmp_img_read(&image, filename); for (int y = 0; y < img_size->height; y += 1) { for (int x = 0; x < img_size->width; x += 1) { RGB->red[y][x] = image.img_pixels[y][x].red; RGB->green[y][x] = image.img_pixels[y][x].green; RGB->blue[y][x] = image.img_pixels[y][x].blue; } } } void save_image(Size* img_size, RGB* RGB, const char* filename) { bmp_img image; bmp_img_init_df(&image, img_size->width, img_size->height); for (int y = 0; y < img_size->height; y += 1) { for (int x = 0; x < img_size->width; x += 1) { bmp_pixel_init( &image.img_pixels[y][x], limit(RGB->red[y][x]), limit(RGB->green[y][x]), limit(RGB->blue[y][x]) ); } } bmp_img_write(&image, filename); bmp_img_free(&image); } Obs: Por algum motivo o fórum deixou o nome do parâmetro RGB maiúsculo. Então para testar tem que corrigir isso.
  17. @Raí Machado Da Silva O enunciado pede para armazenar múltiplos de 5 no vetor. Acho mais fácil dessa forma com o contador C como índice do vetor. Assim para pegar os múltiplos é só adicionar 1 ao contador e multiplicar por 5. Outra forma poderia ser com tentou com a instrução Passo 5. Assim vai incrementar o contador de 5 em 5, aí para pegar o índice do vetor pode usar outra variável para incrementar de 1 em 1, p.ex, N <- 0 Para C <- 5 Ate 50 Passo 5 Faca V[N] <- C N <- N + 1 FimPara
  18. Faltou passar os números para o vetor. Aí só está pegando a variável C. Uma forma simples de armazenar os valores pode ser assim, Para C <- 0 Ate 9 Faca V[C] <- (C + 1) * 5 FimPara
  19. A separação dos parâmetros deve ser com ponto e vírgula e não com vírgula. E na linha 29 o segundo argumento passado para o procedimento deve ser caractere.
  20. Seu programa rodou corretamente aqui, deixando a imagem em preto e branco. Caso o problema não seja o formato da imagem você podia dar mais informações do erro.
  21. O erro deve ser por causa do formato da imagem que tem que ser bmp.
  22. Seu código pode fazer um loop na pasta com a função Dir e testar a data da ultima modificação com FileDateTime. Aí é só pegar o caminho do que tem a maior data e horário.
  23. Se não tiver algum bloqueio ou restrição de segurança vai funcionar normalmente.
  24. @andrevdo Para isso tem a fórmula CONT.SES, p.ex, =CONT.SES($B$3:$B$20;"<>";$D$3:$D$20;F3)

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

 

GRÁTIS: ebook Redes Wi-Fi – 2ª Edição

EBOOK GRÁTIS!

CLIQUE AQUI E BAIXE AGORA MESMO!